code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package cd.go.plugin.config.yaml.transforms; import cd.go.plugin.config.yaml.JsonObjectMatcher; import com.google.gson.JsonObject; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static cd.go.plugin.config.yaml.TestUtils.readJsonObject; import static cd.go.plugin.config.yaml.TestUtils.readYamlObject; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; public class StageTransformTest { private StageTransform parser; private EnvironmentVariablesTransform environmentTransform; private JobTransform jobTransform; @Before public void SetUp() { environmentTransform = new EnvironmentVariablesTransform(); jobTransform = mock(JobTransform.class); parser = new StageTransform(environmentTransform, jobTransform); } @Test public void shouldTransformCompleteStage() throws IOException { testTransform("complete"); } @Test public void shouldTransformShortApprovalStage() throws IOException { testTransform("short_approval"); } @Test public void shouldTransformSingleJobStage() throws IOException { parser = new StageTransform(environmentTransform, new JobTransform(environmentTransform, mock(TaskTransform.class))); testTransform("stage-job"); } private void testTransform(String caseFile) throws IOException { testTransform(caseFile, caseFile); } private void testTransform(String caseFile, String expectedFile) throws IOException { JsonObject expectedObject = (JsonObject) readJsonObject("parts/stages/" + expectedFile + ".json"); JsonObject jsonObject = parser.transform(readYamlObject("parts/stages/" + caseFile + ".yaml")); assertThat(jsonObject, is(new JsonObjectMatcher(expectedObject))); } }
fabiosantos-info/gocd-yaml
src/test/java/cd/go/plugin/config/yaml/transforms/StageTransformTest.java
Java
apache-2.0
1,872
define("clickableguide/bootstrap-3", ["jquery-1", "istats-1", "clickableguide/pubsub"], function(e, s) { var t = function() { if (/iP(hone|od|ad)/.test(navigator.platform)) { var e = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); return [parseInt(e[1], 10), parseInt(e[2], 10), parseInt(e[3] || 0, 10)] >= 5 } return navigator.userAgent.match(/Android 2./) ? !1 : /MSIE 7/.test(navigator.userAgent) ? !1 : !0 }; return { $: e, pubsub: e, empConfig: { paths: { "bump-3": "http://emp.bbci.co.uk/emp/bump-3/bump-3", "jquery-1.9": "http://static.bbci.co.uk/frameworks/jquery/0.3.0/sharedmodules/jquery-1.9.1" } }, istats: s, browserNotOnThePositionFixedNaughtyList: t } }), define("clickableguide/minihash-3", [], function() { var e = function() { this._keysSorted = !1, this._sortedKeys = [], this._map = {}, this.isEmpty = !0, this.size = 0 }; return e.prototype = { keys: function() { e = this; var s, t = []; for (s in e._map) e._map.hasOwnProperty.call(e._map, s) && t.push(s); return t }, values: function() { e = this; var s, t = []; for (s in e._map) e._map.hasOwnProperty.call(e._map, s) && t.push(e._map[s]); return t }, put: function(s, t) { if ("object" == typeof s) throw new Error("TypeError: Keys should be Strings or Numbers"); e = this, e._keysSorted = !1, this._map[s] = t, this.size = this.size + 1, this.isEmpty && (this.isEmpty = !1) }, get: function(e) { return void 0 !== this._map[e] ? this._map[e] : !1 }, del: function(e) { return void 0 !== this._map[e] ? (delete this._map[e], this.size = this.size - 1, 0 === this.size && (this.isEmpty = !0), !0) : !1 }, sortKeys: function() { return e = this, e._keysSorted ? e._sortedKeys : (e._sortedKeys = e.keys().sort(function(e, s) { return e - s }), e._keysSorted = !0, e._sortedKeys) } }, e }), define("clickableguide/carousel-3", ["clickableguide/bootstrap-3"], function(e) { var s = function(s, t, i, n) { this.elm = e.$(s), this.vocab = t, this.pubsubNamespace = "ns-carousel-russell_sq--" + i, this.items = this.elm.find(".ns-carousel-russell_sq__item"), this.currentItem = 0, this.ctaOffset = n - 32, this.addNav(); var a = this; e.pubsub.on(this.pubsubNamespace + ":prev", function() { a.prev() }), e.pubsub.on(this.pubsubNamespace + ":next", function() { a.next() }), e.pubsub.on("ns-panel-russell_sq:show", function(e) { a.fadeInNav(e) }), e.pubsub.on(this.pubsubNamespace + ":show_nav", function(e) { void 0 === e && (e = a.insideVisibleSection()), a.fadeInNav(e) }), e.pubsub.on(this.pubsubNamespace + ":hide_nav", function() { a.fadeOutNav() }), this.elm[0].addEventListener("click", function(s) { a.navDelegation(s), e.pubsub.emit("ns-clickable_guide-russell_sq:carousel:navigated") }, !1), this.elm[0].addEventListener("mouseover", function() { e.pubsub.emit(a.pubsubNamespace + ":show_nav") }, !1), this.elm[0].addEventListener("mouseout", function() { e.pubsub.emit(a.pubsubNamespace + ":hide_nav") }, !1), this.show(0) }; return s.prototype = { fadeInNav: function(e) { (e || this.insideVisibleSection()) && this.elm.find(".ns-carousel-russell_sq__nav").addClass("ns-carousel-russell_sq__nav--faded-in") }, fadeOutNav: function() { this.elm.find(".ns-carousel-russell_sq__nav").removeClass("ns-carousel-russell_sq__nav--faded-in") }, insideVisibleSection: function() { return !!this.elm.find(".ns-carousel-russell_sq__nav").closest(".ns-panel-russell_sq__section--show").length }, show: function(s) { this.currentItem = s, this.items.removeClass("ns-carousel-russell_sq__item--show"), e.$(this.items[s]).addClass("ns-carousel-russell_sq__item--show") }, next: function() { var e = this.currentItem + 1; e >= this.items.length && (e = 0), this.show(e) }, prev: function() { var e = this.currentItem - 1; 0 > e && (e = this.items.length - 1), this.show(e) }, addNav: function() { this.elm.append('<div class="ns-carousel-russell_sq__nav"><a href="#" class="ns-carousel-russell_sq__next-prev ns-carousel-russell_sq__prev" ><span class="ns-panel-russell_sq__hide">' + this.vocab.prevImage + '</span><span class="ns-carousel-russell_sq__arrow-left "></span><span class="ns-carousel-russell_sq__arrow-left--inside"></span></a><a href="#" class="ns-carousel-russell_sq__next-prev ns-carousel-russell_sq__next" ><span class="ns-panel-russell_sq__hide">' + this.vocab.nextImage + '</span><span class="ns-carousel-russell_sq__arrow-right"></span><span class="ns-carousel-russell_sq__arrow-right--inside"></span></a></div>') }, navDelegation: function(s) { var t = e.$(s.target).closest(".ns-carousel-russell_sq__next-prev"); return t.length > 0 && (t.hasClass("ns-carousel-russell_sq__prev") && e.pubsub.emit(this.pubsubNamespace + ":prev"), t.hasClass("ns-carousel-russell_sq__next") && e.pubsub.emit(this.pubsubNamespace + ":next")), s.preventDefault(), s.stopPropagation(), !1 } }, s }), define("clickableguide/imager-3", ["clickableguide/bootstrap-3"], function(e) { var s = function(e) { this.widths = e.availableWidths || [320, 640, 1024], this.regex = e.regex || /^(.+\/)\d+$/i, this.is_resizing = !1, this.onImagesReplaced = e.onImagesReplaced || function() {}, this.change_divs_to_imgs(), this.init_resize_images() }; return s.prototype = { change_divs_to_imgs: function() { var s = this; e.$(".idt-delayed-image-load-russell_sq").each(function(t, i) { var n = e.$(i); i.className.search("js-no_replace") > -1 || setTimeout(function() { n.removeClass("delayed-image-load"); var t = e.$('<img src="' + s.calc_img_src(n.attr("data-src"), n.width()) + '" alt="' + (n.attr("data-alt") || "") + '" class="js-image_replace ' + n.attr("class") + '" />'); n.after(t) }, 1) }) }, calc_img_src: function(e, s) { return null === e ? !1 : e.replace(/(\/{cg_width}\/)/, "/" + this.match_closest_value(s, this.widths) + "/") }, match_closest_value: function(e, s) { for (var t = s[0], i = 0, n = s.length; n > i; i++) { if (e < s[i]) return t; t = s[i] } return t }, init_resize_images: function() { var e = this; window.addEventListener("resize", function() { e.resize_images() }, !1) }, resize_images: function() { var s = e.$(".js-image_replace"), t = this; this.is_resizing || (this.is_resizing = !0, null !== s && s.each(function() { if (!e.$(this).hasClass("js-no_replace")) { var s = t.calc_img_src(this.getAttribute("datasrc") || this.src, this.clientWidth); s && this.src !== s && (this.src = s) } }), this.is_resizing = !1, this.onImagesReplaced()) } }, s }), define("js/clickableguide/main-3", ["clickableguide/bootstrap-3", "clickableguide/minihash-3", "clickableguide/carousel-3", "clickableguide/imager-3"], function(e, s, t, i) { var n = function(s, t, i) { this.elm = e.$(s), this.vocab = t, this.opts = i || { panelPosition: "centre_of_interactive" }, this.initPanels(), this.initCarousels(), this.callImager(this.opts), this.applyOptions(this.opts), this.setupPubsubs(), this.empVisible = !1, this.tellIstatsTheInitialLayoutMode(e.$(window).width(), e.$(window).height(), i), this.setResponsiveSiteToBeFullWidth(this.opts) }; return n.prototype = { initPanels: function() { this.panels = new s, this.empPanels = new s, this.buildMiniHash(this.elm.find(".ns-panel-russell_sq__section--int"), this.panels), this.buildMiniHash(this.elm.find(".ns-panel-russell_sq__section--emp"), this.empPanels), this.currentPanel = this.panels.sortKeys()[0], this.poster = "" }, initCarousels: function() { var e = this; this.elm.find(".ns-carousel-russell_sq").each(function(s) { { var i = this; new t(i, e.vocab, e.createUniqueId(), e.getOffsetValue(s)) } }) }, applyOptions: function(e) { e.panelsPosition = e.panelsPosition || "default", this.choosePanelPosition(e.panelsPosition), this.addMask(e.mask), this.setMinWidthAndHeight(e), e.nextPrevButtons && this.addNextPrevButtons() }, setupPubsubs: function() { this.listenForPubsubEvents(), this.listenForClicks() }, callImager: function(s) { var t = { availableWidths: [96, 130, 165, 200, 235, 270, 304, 340, 375, 410, 445, 485, 520, 555, 590, 625, 660, 695, 736, 772, 800, 834, 872, 904, 936, 976], onImagesReplaced: function() { var t = s.panelsPosition || "default"; e.pubsub.emit("ns-clickable_guide-russell_sq:imager:updated", [t]) } }; s.responsive || (t.onResize = !1), new i(t) }, listenForPubsubEvents: function() { var s = this; e.pubsub.on("ns-panel-russell_sq:show", function(t) { s.hide(), s.choosePanelPosition(s.opts.panelsPosition), s.show(t), e.istats.log("open-panel", "newsindep-interaction", { view: t }) }), e.pubsub.on("ns-panel-russell_sq:hide", function() { s.hide() }), e.pubsub.on("ns-clickable_guide-russell_sq:imager:updated", function(e) { s.choosePanelPosition(e) }), e.pubsub.on("ns-clickable_guide-russell_sq:carousel:navigated", function() {}) }, listenForClicks: function() { var s = this; e.$(".ns-panel-russell_sq__hotspot ").click(function(e) { return s.preventDefaults(e, function() { s.launchPanel(e, s) }) }), e.$(".ns-panel-russell_sq__video__cta").on("mousedown", function(e) { return s.preventDefaults(e, function() { s.launchPanel(e, s), s.isVideoInViewport(e.currentTarget) || e.currentTarget.scrollIntoView(!1) }) }), e.$(".ns-panel-russell_sq__prev").click(function(e) { return s.preventDefaults(e, function() { s.prev() }) }), e.$(".ns-panel-russell_sq__next").click(function(e) { return s.preventDefaults(e, function() { s.next() }) }), e.$(".ns-panel-russell_sq__section-close").click(function(t) { return s.preventDefaults(t, function() { e.pubsub.emit("ns-panel-russell_sq:hide") }) }), this.maskElm && this.maskElm[0].addEventListener("click", function() { e.pubsub.emit("ns-panel-russell_sq:hide") }, !1) }, launchPanel: function(s, t) { var i = t.getPanelIndexFromHref(e.$(s.currentTarget).attr("href")); e.pubsub.emit("ns-panel-russell_sq:show", [i]) }, getPanelIndexFromHref: function(e) { return e.replace(/^\D+/g, "") }, setMinWidthAndHeight: function(s) { var t = this; t.interactiveMinWidth = 0, t.interactiveMinHeight = 0, s.interactiveMinWidth && s.responsive && s.interactiveMinHeight && (this.interactiveMinWidth = s.interactiveMinWidth, this.interactiveMinHeight = s.interactiveMinHeight, window.addEventListener("resize", function() { t.showHideClickableGuide(e.$(window).width(), e.$(window).height()) }, !1)), this.showHideClickableGuide(e.$(window).width(), e.$(window).height()) }, buildMiniHash: function(s, t) { s.each(function() { var s = e.$(this); t.put(s.attr("id").split("section-")[1], s) }) }, getOffsetValue: function(s) { return e.$(this.panels.get(s)).find(".ns-panel-russell_sq__section-header").outerHeight(!0) || 0 + e.$(this.panels.get(s)).find(".ns-panel-russell_sq__section-sub-header").outerHeight(!0) || 0 }, getContextSize: function() { return this.elm.find(".ns-panel-russell_sq__hotspots>img").outerHeight(!0) + this.elm.find(".ns-panel-russell_sq__clickable").outerHeight(!0) }, createUniqueId: function() { return this.elm.attr("id") + (new Date).getTime() }, loadBump: function(s) { var t = this; require(e.empConfig, ["bump-3"], function(e) { t.loadEmp(e, s) }) }, loadEmp: function(s, t) { var i = this, n = t.find(".ns-panel-russell_sq__section-emp-data"), a = n.attr("data-playlist"), o = (new Date).getTime(); this.poster = t.find(".ns-panel-russell_sq__section-emp-img"), this.empVisible || (this.empVisible = !0, i.elm.append('<div id="ns-player--' + o + '" class="ns-panel-russell_sq__emp_player"></div>'), i.emp = { elm: e.$("#ns-player--" + o), player: s("#ns-player--" + o).player({ product: "news", playerProfile: a, responsive: !1, autoplay: !0 }) }), this.poster.addClass("ns-panel-russell_sq__section-emp-img--hide"), i.emp.player.poster(this.poster.attr("src")), i.sizeEmp(), i.emp.player.load(a), n.after(i.emp.elm) }, sizeEmp: function() { this.empVisible && null !== this.poster.width() && null !== this.poster.height() && (this.emp.player.width(this.poster.width().toString() || "640"), this.emp.player.height((.5625 * this.emp.player.width()).toString() || "360")) }, hideEmp: function() { e.$(".ns-panel-russell_sq__section-emp-img").removeClass("ns-panel-russell_sq__section-emp-img--hide"), this.empVisible && (this.elm.find(".ns-panel-russell_sq__emp_player").remove(), this.empVisible = !1) }, show: function(s) { this.hide(), this.currentPanel = s; var t = e.$(this.panels.get(s)); t.addClass("ns-panel-russell_sq__section--show"), this.setHotspotActiveState(s), this.maskElm && (this.showMask(), this.maskElm.height(e.$("#blq-container-outer, #blq-container")[0].clientHeight)), this.empPanels.get(s) !== !1 ? this.loadBump(t) : this.hideEmp() }, hide: function() { this.hideEmp(), this.elm.find(".ns-panel-russell_sq__section--show").removeClass("ns-panel-russell_sq__section--show"), this.currentPanel = this.panels.sortKeys()[0], this.hideMask(), this.setHotspotActiveState(0) }, next: function() { var s, t = this.panels.sortKeys(); t.indexOf(this.currentPanel) === t.length - 1 ? s = this.currentPanel : (s = t[t.indexOf(this.currentPanel) + 1], e.pubsub.emit("ns-panel-russell_sq:show", [s])) }, prev: function() { var s = this.panels.sortKeys(); if (s.indexOf(this.currentPanel) > 0) { var t = s[s.indexOf(this.currentPanel) - 1]; e.pubsub.emit("ns-panel-russell_sq:show", [t]) } }, addNextPrevButtons: function() { for (var s = this, t = s.panels.sortKeys(), i = 0; i < s.panels.size; i++) { var n = t[i], a = '<a href="#ns-panel-russell_sq__section-' + t[i - 1] + '" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__prev">', o = '<a href="#ns-panel-russell_sq__section-' + t[i + 1] + '" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__next">'; 0 === i ? a = '<a href="#" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__prev ns-panel-russell_sq__next-prev--disabled">' : i === s.panels.size - 1 && (o = '<a href="#" class="ns-panel-russell_sq__next-prev ns-panel-russell_sq__next ns-panel-russell_sq__next-prev--disabled">'), e.$(s.panels.get(n)).append('<div class="ns-panel-russell_sq__section-nav">' + a + '<span class="ns-panel-russell_sq__hide">' + s.vocab.prev + '</span><span class="ns-panel-russell_sq__arrow-left "></span><span class="ns-panel-russell_sq__arrow-left--inside"></span></a><div class="ns-panel-russell_sq__counter"> ' + (i + 1) + " " + s.vocab.pagingDivider + " " + s.panels.size + " </div>" + o + '<span class="ns-panel-russell_sq__hide">' + s.vocab.next + '</span><span class="ns-panel-russell_sq__arrow-right"></span><span class="ns-panel-russell_sq__arrow-right--inside"></span></a></div>') } }, showHideClickableGuide: function(e, s) { this.viewportIsBigEnoughForClickableGuide(e, s) ? (this.elm.addClass("ns-panel-russell_sq--interactive"), 0 !== this.currentPanel && this.showMask()) : (this.elm.removeClass("ns-panel-russell_sq--interactive"), this.hideMask()), this.sizeEmp() }, viewportIsBigEnoughForClickableGuide: function(e, s) { return e >= this.interactiveMinWidth && s >= this.interactiveMinHeight }, tellIstatsTheInitialLayoutMode: function(s, t, i) { var n = "list"; (this.viewportIsBigEnoughForClickableGuide(s, t) || i.responsive !== !0) && (n = "interactive"), e.istats.log("layout-mode", "newsindep-nonuser", { view: n }) }, addMask: function(s) { ("white" === s || "black" === s) && (e.$("body").append('<div class="ns-panel-russell_sq__mask ns-panel-russell_sq__mask--' + s + '"></div>'), this.maskElm = e.$(".ns-panel-russell_sq__mask")) }, showMask: function() { this.maskElm && (this.maskElm.addClass("ns-panel-russell_sq__mask--show"), this.maskElm.height(e.$("body").height())) }, hideMask: function() { this.maskElm && this.maskElm.removeClass("ns-panel-russell_sq__mask--show") }, preventDefaults: function(e, s) { return e.preventDefault(), e.stopPropagation(), s(), !1 }, choosePanelPosition: function(s) { var t, i, n = this; if ("default" === s || "centre_of_interactive" === s) for (t in n.panels._map) i = n.panels.get(t), i.css({ top: (n.getContextSize() - i.height()) / 2 + "px" }); else if ("right_of_interactive" === s) for (t in n.panels._map) i = n.panels.get(t), i.addClass("ns-panel-russell_sq__section--align-right"); else if ("centre_of_screen" === s && e.browserNotOnThePositionFixedNaughtyList) for (t in n.panels._map) i = n.panels.get(t), i.addClass("ns-panel-russell_sq__section--centre_of_screen"), i.css({ marginTop: "-" + i.height() / 2 + "px", marginLeft: "-" + i.width() / 2 + "px" }) }, isVideoInViewport: function(e) { var s = e.getBoundingClientRect(); return s.top >= 0 && s.left >= 0 && s.bottom <= (window.innerHeight || document.documentElement.clientHeight) && s.right <= (window.innerWidth || document.documentElement.clientWidth) }, setHotspotActiveState: function(s) { e.$(".ns-panel-russell_sq__hotspot").removeClass("ns-panel-russell_sq__hotspot--active"), e.$(".ns-panel-russell_sq__hotspot--" + s).addClass("ns-panel-russell_sq__hotspot--active") }, setResponsiveSiteToBeFullWidth: function(e) { "interactiveMinWidth" in e && e.interactiveMinWidth >= 976 } }, n }); //# sourceMappingURL=ns_clickableguide_all.js //# sourceMappingURL=ns_clickableguide_all.js.map
BBCVisualJournalism/newsspec_11531
russell_sq/ns_clickableguide_all-russell_sq.js
JavaScript
apache-2.0
20,724
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.server.communication; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.vaadin.server.ClientConnector; import com.vaadin.server.JsonPaintTarget; import com.vaadin.server.LegacyCommunicationManager; import com.vaadin.server.LegacyCommunicationManager.ClientCache; import com.vaadin.server.SystemMessages; import com.vaadin.server.VaadinService; import com.vaadin.server.VaadinSession; import com.vaadin.shared.ApplicationConstants; import com.vaadin.ui.ConnectorTracker; import com.vaadin.ui.Dependency; import com.vaadin.ui.UI; import elemental.json.Json; import elemental.json.JsonArray; import elemental.json.JsonObject; import elemental.json.impl.JsonUtil; /** * Serializes pending server-side changes to UI state to JSON. This includes * shared state, client RPC invocations, connector hierarchy changes, connector * type information among others. * * @author Vaadin Ltd * @since 7.1 */ public class UidlWriter implements Serializable { /** * Writes a JSON object containing all pending changes to the given UI. * * @param ui * The {@link UI} whose changes to write * @param writer * The writer to use * @param async * True if this message is sent by the server asynchronously, * false if it is a response to a client message. * * @throws IOException * If the writing fails. */ public void write(UI ui, Writer writer, boolean async) throws IOException { VaadinSession session = ui.getSession(); VaadinService service = session.getService(); // Purge pending access calls as they might produce additional changes // to write out service.runPendingAccessTasks(session); Set<ClientConnector> processedConnectors = new HashSet<>(); LegacyCommunicationManager manager = session.getCommunicationManager(); ClientCache clientCache = manager.getClientCache(ui); boolean repaintAll = clientCache.isEmpty(); // Paints components ConnectorTracker uiConnectorTracker = ui.getConnectorTracker(); getLogger().log(Level.FINE, "* Creating response to client"); while (true) { ArrayList<ClientConnector> connectorsToProcess = new ArrayList<>(); for (ClientConnector c : uiConnectorTracker.getDirtyConnectors()) { if (!processedConnectors.contains(c) && LegacyCommunicationManager .isConnectorVisibleToClient(c)) { connectorsToProcess.add(c); } } if (connectorsToProcess.isEmpty()) { break; } for (ClientConnector connector : connectorsToProcess) { boolean initialized = uiConnectorTracker .isClientSideInitialized(connector); processedConnectors.add(connector); try { connector.beforeClientResponse(!initialized); } catch (RuntimeException e) { manager.handleConnectorRelatedException(connector, e); } } } getLogger().log(Level.FINE, "Found " + processedConnectors.size() + " dirty connectors to paint"); uiConnectorTracker.setWritingResponse(true); try { int syncId = service.getDeploymentConfiguration() .isSyncIdCheckEnabled() ? uiConnectorTracker.getCurrentSyncId() : -1; writer.write("\"" + ApplicationConstants.SERVER_SYNC_ID + "\": " + syncId + ", "); if (repaintAll) { writer.write("\"" + ApplicationConstants.RESYNCHRONIZE_ID + "\": true, "); } int nextClientToServerMessageId = ui .getLastProcessedClientToServerId() + 1; writer.write("\"" + ApplicationConstants.CLIENT_TO_SERVER_ID + "\": " + nextClientToServerMessageId + ", "); writer.write("\"changes\" : "); JsonPaintTarget paintTarget = new JsonPaintTarget(manager, writer, !repaintAll); new LegacyUidlWriter().write(ui, writer, paintTarget); paintTarget.close(); writer.write(", "); // close changes // send shared state to client // for now, send the complete state of all modified and new // components // Ideally, all this would be sent before "changes", but that causes // complications with legacy components that create sub-components // in their paint phase. Nevertheless, this will be processed on the // client after component creation but before legacy UIDL // processing. writer.write("\"state\":"); Set<String> stateUpdateConnectors = new SharedStateWriter() .write(ui, writer); writer.write(", "); // close states // TODO This should be optimized. The type only needs to be // sent once for each connector id + on refresh. Use the same cache // as // widget mapping writer.write("\"types\":"); new ConnectorTypeWriter().write(ui, writer, paintTarget); writer.write(", "); // close states // Send update hierarchy information to the client. // This could be optimized aswell to send only info if hierarchy has // actually changed. Much like with the shared state. Note though // that an empty hierarchy is information aswell (e.g. change from 1 // child to 0 children) writer.write("\"hierarchy\":"); new ConnectorHierarchyWriter().write(ui, writer, stateUpdateConnectors); writer.write(", "); // close hierarchy // send server to client RPC calls for components in the UI, in call // order // collect RPC calls from components in the UI in the order in // which they were performed, remove the calls from components writer.write("\"rpc\" : "); new ClientRpcWriter().write(ui, writer); writer.write(", "); // close rpc uiConnectorTracker.markAllConnectorsClean(); writer.write("\"meta\" : "); SystemMessages messages = ui.getSession().getService() .getSystemMessages(ui.getLocale(), null); // TODO hilightedConnector new MetadataWriter().write(ui, writer, repaintAll, async, messages); writer.write(", "); writer.write("\"resources\" : "); new ResourceWriter().write(ui, writer, paintTarget); Collection<Class<? extends ClientConnector>> usedClientConnectors = paintTarget .getUsedClientConnectors(); boolean typeMappingsOpen = false; List<Class<? extends ClientConnector>> newConnectorTypes = new ArrayList<>(); for (Class<? extends ClientConnector> class1 : usedClientConnectors) { if (clientCache.cache(class1)) { // client does not know the mapping key for this type, send // mapping to client newConnectorTypes.add(class1); if (!typeMappingsOpen) { typeMappingsOpen = true; writer.write(", \"typeMappings\" : { "); } else { writer.write(" , "); } String canonicalName = class1.getCanonicalName(); writer.write("\""); writer.write(canonicalName); writer.write("\" : "); writer.write(manager.getTagForType(class1)); } } if (typeMappingsOpen) { writer.write(" }"); } // TODO PUSH Refactor to TypeInheritanceWriter or something boolean typeInheritanceMapOpen = false; if (typeMappingsOpen) { // send the whole type inheritance map if any new mappings for (Class<? extends ClientConnector> class1 : usedClientConnectors) { if (!ClientConnector.class .isAssignableFrom(class1.getSuperclass())) { continue; } if (!typeInheritanceMapOpen) { typeInheritanceMapOpen = true; writer.write(", \"typeInheritanceMap\" : { "); } else { writer.write(" , "); } writer.write("\""); writer.write(manager.getTagForType(class1)); writer.write("\" : "); writer.write(manager.getTagForType( (Class<? extends ClientConnector>) class1 .getSuperclass())); } if (typeInheritanceMapOpen) { writer.write(" }"); } } // TODO Refactor to DependencyWriter or something /* * Ensure super classes come before sub classes to get script * dependency order right. Sub class @JavaScript might assume that * * @JavaScript defined by super class is already loaded. */ Collections.sort(newConnectorTypes, new Comparator<Class<?>>() { @Override public int compare(Class<?> o1, Class<?> o2) { // TODO optimize using Class.isAssignableFrom? return hierarchyDepth(o1) - hierarchyDepth(o2); } private int hierarchyDepth(Class<?> type) { if (type == Object.class) { return 0; } else { return hierarchyDepth(type.getSuperclass()) + 1; } } }); List<Dependency> dependencies = Dependency .findDependencies(newConnectorTypes, manager); // Include dependencies in output if there are any if (!dependencies.isEmpty()) { writer.write(", \"dependencies\": " + JsonUtil.stringify(toJsonArray(dependencies))); } session.getDragAndDropService().printJSONResponse(writer); for (ClientConnector connector : processedConnectors) { uiConnectorTracker.markClientSideInitialized(connector); } assert (uiConnectorTracker.getDirtyConnectors() .isEmpty()) : "Connectors have been marked as dirty during the end of the paint phase. This is most certainly not intended."; writePerformanceData(ui, writer); } finally { uiConnectorTracker.setWritingResponse(false); uiConnectorTracker.cleanConnectorMap(); } } private JsonArray toJsonArray(List<Dependency> list) { JsonArray result = Json.createArray(); for (int i = 0; i < list.size(); i++) { JsonObject dep = Json.createObject(); Dependency dependency = list.get(i); dep.put("type", dependency.getType().name()); dep.put("url", dependency.getUrl()); result.set(i, dep); } return result; } /** * Adds the performance timing data (used by TestBench 3) to the UIDL * response. * * @throws IOException */ private void writePerformanceData(UI ui, Writer writer) throws IOException { if (!ui.getSession().getService().getDeploymentConfiguration() .isProductionMode()) { writer.write(String.format(", \"timings\":[%d, %d]", ui.getSession().getCumulativeRequestDuration(), ui.getSession().getLastRequestDuration())); } } private static final Logger getLogger() { return Logger.getLogger(UidlWriter.class.getName()); } }
Legioth/vaadin
server/src/main/java/com/vaadin/server/communication/UidlWriter.java
Java
apache-2.0
13,300
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Wizchat.Models { public class LoginRequest { public string Name { get; set; } public string ConnectionId { get; set; } } }
nimesh89/wizchat
Wizchat/Models/LoginRequest.cs
C#
apache-2.0
263
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.fraud; import java.math.BigDecimal; import com.example.fraud.model.FraudCheck; import com.example.fraud.model.FraudCheckResult; import com.example.fraud.model.FraudCheckStatus; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.web.bind.annotation.RequestMethod.PUT; @RestController public class FraudDetectionController { private static final String NO_REASON = null; private static final String AMOUNT_TOO_HIGH = "Amount too high"; private static final BigDecimal MAX_AMOUNT = new BigDecimal("5000"); // tag::server_api[] @RequestMapping(value = "/fraudcheck", method = PUT) public FraudCheckResult fraudCheck(@RequestBody FraudCheck fraudCheck) { // end::server_api[] // tag::new_impl[] if (amountGreaterThanThreshold(fraudCheck)) { return new FraudCheckResult(FraudCheckStatus.FRAUD, AMOUNT_TOO_HIGH); } // end::new_impl[] // tag::initial_impl[] return new FraudCheckResult(FraudCheckStatus.OK, NO_REASON); // end::initial_impl[] } @RequestMapping(value = "/pactfraudcheck", method = PUT) public FraudCheckResult pactFraudCheck(@RequestBody FraudCheck fraudCheck) { return fraudCheck(fraudCheck); } @RequestMapping(value = "/yamlfraudcheck", method = PUT) public FraudCheckResult yamlFraudCheck(@RequestBody FraudCheck fraudCheck) { return fraudCheck(fraudCheck); } private boolean amountGreaterThanThreshold(FraudCheck fraudCheck) { return MAX_AMOUNT.compareTo(fraudCheck.getLoanAmount()) < 0; } }
spring-cloud/spring-cloud-contract
samples/standalone/dsl/http-server/src/main/java/com/example/fraud/FraudDetectionController.java
Java
apache-2.0
2,268
package org.javers.spring.boot.mongo; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; import org.javers.core.Javers; import org.javers.core.JaversBuilder; import org.javers.core.MappingStyle; import org.javers.core.diff.ListCompareAlgorithm; import org.javers.repository.api.JaversRepository; import org.javers.repository.mongo.MongoRepository; import org.javers.spring.auditable.AuthorProvider; import org.javers.spring.auditable.aspect.JaversAuditableRepositoryAspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.mongo.MongoProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; /** * @author pawelszymczyk */ @Configuration @EnableAspectJAutoProxy @EnableConfigurationProperties({JaversProperties.class}) public class JaversMongoAutoConfiguration { private static final Logger logger = LoggerFactory.getLogger(JaversMongoAutoConfiguration.class); @Autowired private JaversProperties javersProperties; @Autowired private MongoClient mongoClient; //from spring-boot-starter-data-mongodb @Autowired private MongoProperties mongoProperties; //from spring-boot-starter-data-mongodb @Bean public Javers javers() { logger.info("Starting javers-spring-boot-starter-mongo ..."); MongoDatabase mongoDatabase = mongoClient.getDatabase( mongoProperties.getMongoClientDatabase() ); logger.info("connecting to database: {}", mongoProperties.getMongoClientDatabase()); JaversRepository javersRepository = new MongoRepository(mongoDatabase); return JaversBuilder.javers() .withListCompareAlgorithm(ListCompareAlgorithm.valueOf(javersProperties.getAlgorithm().toUpperCase())) .withMappingStyle(MappingStyle.valueOf(javersProperties.getMappingStyle().toUpperCase())) .withNewObjectsSnapshot(javersProperties.isNewObjectSnapshot()) .withPrettyPrint(javersProperties.isPrettyPrint()) .withTypeSafeValues(javersProperties.isTypeSafeValues()) .registerJaversRepository(javersRepository) .build(); } @Bean @ConditionalOnMissingBean public AuthorProvider authorProvider() { return new AuthorProvider() { public String provide() { return "unknown"; } }; } @Bean public JaversAuditableRepositoryAspect javersAuditableRepositoryAspect(Javers javers, AuthorProvider authorProvider) { return new JaversAuditableRepositoryAspect(javers, authorProvider); } }
ramasinka/javers
javers-spring-boot-starter-mongo/src/main/java/org/javers/spring/boot/mongo/JaversMongoAutoConfiguration.java
Java
apache-2.0
2,980
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.chinamobile.bcbsp.io; import com.chinamobile.bcbsp.util.BSPJob; import java.io.IOException; /** * RecordWriter This class can write a record in the format of Key-Value. */ public abstract class RecordWriter<K, V> { /** * Writes a key/value pair. <code>RecordWriter</code> writes the output * &lt;key, value&gt; pairs to an output file. * * @param key * the key to write. * @param value * the value to write. * @throws IOException */ public abstract void write(K key, V value) throws IOException, InterruptedException; /** * Writes a key/value pair. <code>RecordWriter</code> writes the output * &lt;key, value&gt; pairs to an output file. * * @param key * the key to write. * @param value * the value to write. * @throws IOException */ public abstract void write(K keyValue) throws IOException, InterruptedException; /** * Close this <code>RecordWriter</code> to future operations. * * @param job * The current BSPJob job * @throws IOException */ public abstract void close(BSPJob job) throws IOException, InterruptedException; }
LiuJianan/Graduate-Graph
src/java/com/chinamobile/bcbsp/io/RecordWriter.java
Java
apache-2.0
1,997
package com.foxconn.crd.common.adapter; import android.view.View; /** * Created by qinicy on 16/1/28. */ public interface OnItemClickListener<T> { public void onClick(View view, T obj); }
qinicy/DailyQuery
common/src/main/java/com/foxconn/crd/common/adapter/OnItemClickListener.java
Java
apache-2.0
196
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq; import javax.jms.Topic; import javax.jms.TextMessage; public class JmsTopicSendSameMessageTest extends JmsTopicSendReceiveWithTwoConnectionsTest { private static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory .getLog(JmsTopicSendSameMessageTest.class); public void testSendReceive() throws Exception { messages.clear(); TextMessage message = session.createTextMessage(); for (int i = 0; i < data.length; i++) { message.setText(data[i]); message.setStringProperty("stringProperty", data[i]); message.setIntProperty("intProperty", i); if (verbose) { LOG.info("About to send a message: " + message + " with text: " + data[i]); } producer.send(producerDestination, message); } assertMessagesAreReceived(); } }
mocc/bookkeeper-lab
hedwig-client-jms/src/test/java/org/apache/activemq/JmsTopicSendSameMessageTest.java
Java
apache-2.0
1,730
/* * Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.impl.migration; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotContainsNull; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotEmpty; import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import org.camunda.bpm.application.ProcessApplicationReference; import org.camunda.bpm.engine.BadUserRequestException; import org.camunda.bpm.engine.impl.ProcessEngineLogger; import org.camunda.bpm.engine.impl.cfg.CommandChecker; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.context.ProcessApplicationContextUtil; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.migration.instance.DeleteUnmappedInstanceVisitor; import org.camunda.bpm.engine.impl.migration.instance.MigratingActivityInstance; import org.camunda.bpm.engine.impl.migration.instance.MigratingActivityInstanceVisitor; import org.camunda.bpm.engine.impl.migration.instance.MigratingCompensationEventSubscriptionInstance; import org.camunda.bpm.engine.impl.migration.instance.MigratingEventScopeInstance; import org.camunda.bpm.engine.impl.migration.instance.MigratingProcessElementInstanceTopDownWalker; import org.camunda.bpm.engine.impl.migration.instance.MigratingProcessInstance; import org.camunda.bpm.engine.impl.migration.instance.MigratingScopeInstance; import org.camunda.bpm.engine.impl.migration.instance.MigratingScopeInstanceBottomUpWalker; import org.camunda.bpm.engine.impl.migration.instance.MigratingTransitionInstance; import org.camunda.bpm.engine.impl.migration.instance.MigrationCompensationInstanceVisitor; import org.camunda.bpm.engine.impl.migration.instance.parser.MigratingInstanceParser; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingActivityInstanceValidationReportImpl; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingActivityInstanceValidator; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingCompensationInstanceValidator; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingProcessInstanceValidationReportImpl; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingTransitionInstanceValidationReportImpl; import org.camunda.bpm.engine.impl.migration.validation.instance.MigratingTransitionInstanceValidator; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity; import org.camunda.bpm.engine.impl.tree.ReferenceWalker; import org.camunda.bpm.engine.migration.MigrationPlan; /** * How migration works: * * <ol> * <li>Validate migration instructions. * <li>Delete activity instances that are not going to be migrated, invoking execution listeners * and io mappings. This is performed in a bottom-up fashion in the activity instance tree and ensures * that the "upstream" tree is always consistent with respect to the old process definition. * <li>Migrate and create activity instances. Creation invokes execution listeners * and io mappings. This is performed in a top-down fashion in the activity instance tree and * ensures that the "upstream" tree is always consistent with respect to the new process definition. * </ol> * @author Thorben Lindhauer */ public class MigrateProcessInstanceCmd extends AbstractMigrationCmd<Void> { protected static final MigrationLogger LOGGER = ProcessEngineLogger.MIGRATION_LOGGER; protected boolean writeOperationLog; public MigrateProcessInstanceCmd(MigrationPlanExecutionBuilderImpl migrationPlanExecutionBuilder, boolean writeOperationLog) { super(migrationPlanExecutionBuilder); this.writeOperationLog = writeOperationLog; } public Void execute(final CommandContext commandContext) { final MigrationPlan migrationPlan = executionBuilder.getMigrationPlan(); final Collection<String> processInstanceIds = collectProcessInstanceIds(commandContext); ensureNotNull(BadUserRequestException.class, "Migration plan cannot be null", "migration plan", migrationPlan); ensureNotEmpty(BadUserRequestException.class, "Process instance ids cannot empty", "process instance ids", processInstanceIds); ensureNotContainsNull(BadUserRequestException.class, "Process instance ids cannot be null", "process instance ids", processInstanceIds); ProcessDefinitionEntity sourceDefinition = resolveSourceProcessDefinition(commandContext); final ProcessDefinitionEntity targetDefinition = resolveTargetProcessDefinition(commandContext); checkAuthorizations(commandContext, sourceDefinition, targetDefinition, processInstanceIds); if (writeOperationLog) { writeUserOperationLog(commandContext, sourceDefinition, targetDefinition, processInstanceIds.size(), false); } commandContext.runWithoutAuthorization(new Callable<Void>() { @Override public Void call() throws Exception { for (String processInstanceId : processInstanceIds) { migrateProcessInstance(commandContext, processInstanceId, migrationPlan, targetDefinition); } return null; } }); return null; } public Void migrateProcessInstance(CommandContext commandContext, String processInstanceId, MigrationPlan migrationPlan, ProcessDefinitionEntity targetProcessDefinition) { ensureNotNull(BadUserRequestException.class, "Process instance id cannot be null", "process instance id", processInstanceId); final ExecutionEntity processInstance = commandContext.getExecutionManager().findExecutionById(processInstanceId); ensureProcessInstanceExist(processInstanceId, processInstance); ensureOperationAllowed(commandContext, processInstance, targetProcessDefinition); ensureSameProcessDefinition(processInstance, migrationPlan.getSourceProcessDefinitionId()); MigratingProcessInstanceValidationReportImpl processInstanceReport = new MigratingProcessInstanceValidationReportImpl(); // Initialize migration: match migration instructions to activity instances and collect required entities MigratingInstanceParser migratingInstanceParser = new MigratingInstanceParser(Context.getProcessEngineConfiguration().getProcessEngine()); final MigratingProcessInstance migratingProcessInstance = migratingInstanceParser.parse(processInstance.getId(), migrationPlan, processInstanceReport); validateInstructions(commandContext, migratingProcessInstance, processInstanceReport); if (processInstanceReport.hasFailures()) { throw LOGGER.failingMigratingProcessInstanceValidation(processInstanceReport); } executeInContext( new Runnable() { @Override public void run() { deleteUnmappedActivityInstances(migratingProcessInstance); } }, migratingProcessInstance.getSourceDefinition()); executeInContext( new Runnable() { @Override public void run() { migrateProcessInstance(migratingProcessInstance); } }, migratingProcessInstance.getTargetDefinition()); return null; } protected <T> void executeInContext(final Runnable runnable, ProcessDefinitionEntity contextDefinition) { ProcessApplicationContextUtil.doContextSwitch(runnable, contextDefinition); } /** * delete unmapped instances in a bottom-up fashion (similar to deleteCascade and regular BPMN execution) */ protected void deleteUnmappedActivityInstances(MigratingProcessInstance migratingProcessInstance) { Set<MigratingScopeInstance> leafInstances = collectLeafInstances(migratingProcessInstance); final DeleteUnmappedInstanceVisitor visitor = new DeleteUnmappedInstanceVisitor(executionBuilder.isSkipCustomListeners(), executionBuilder.isSkipIoMappings()); for (MigratingScopeInstance leafInstance : leafInstances) { MigratingScopeInstanceBottomUpWalker walker = new MigratingScopeInstanceBottomUpWalker(leafInstance); walker.addPreVisitor(visitor); walker.walkUntil(new ReferenceWalker.WalkCondition<MigratingScopeInstance>() { @Override public boolean isFulfilled(MigratingScopeInstance element) { // walk until top of instance tree is reached or until // a node is reached for which we have not yet visited every child return element == null || !visitor.hasVisitedAll(element.getChildScopeInstances()); } }); } } protected Set<MigratingScopeInstance> collectLeafInstances(MigratingProcessInstance migratingProcessInstance) { Set<MigratingScopeInstance> leafInstances = new HashSet<MigratingScopeInstance>(); for (MigratingScopeInstance migratingScopeInstance : migratingProcessInstance.getMigratingScopeInstances()) { if (migratingScopeInstance.getChildScopeInstances().isEmpty()) { leafInstances.add(migratingScopeInstance); } } return leafInstances; } protected void validateInstructions(CommandContext commandContext, MigratingProcessInstance migratingProcessInstance, MigratingProcessInstanceValidationReportImpl processInstanceReport) { List<MigratingActivityInstanceValidator> migratingActivityInstanceValidators = commandContext.getProcessEngineConfiguration().getMigratingActivityInstanceValidators(); List<MigratingTransitionInstanceValidator> migratingTransitionInstanceValidators = commandContext.getProcessEngineConfiguration().getMigratingTransitionInstanceValidators(); List<MigratingCompensationInstanceValidator> migratingCompensationInstanceValidators = commandContext.getProcessEngineConfiguration().getMigratingCompensationInstanceValidators(); Map<MigratingActivityInstance, MigratingActivityInstanceValidationReportImpl> instanceReports = new HashMap<MigratingActivityInstance, MigratingActivityInstanceValidationReportImpl>(); for (MigratingActivityInstance migratingActivityInstance : migratingProcessInstance.getMigratingActivityInstances()) { MigratingActivityInstanceValidationReportImpl instanceReport = validateActivityInstance(migratingActivityInstance, migratingProcessInstance, migratingActivityInstanceValidators); instanceReports.put(migratingActivityInstance, instanceReport); } for (MigratingEventScopeInstance migratingEventScopeInstance : migratingProcessInstance.getMigratingEventScopeInstances()) { MigratingActivityInstance ancestorInstance = migratingEventScopeInstance.getClosestAncestorActivityInstance(); validateEventScopeInstance( migratingEventScopeInstance, migratingProcessInstance, migratingCompensationInstanceValidators, instanceReports.get(ancestorInstance)); } for (MigratingCompensationEventSubscriptionInstance migratingEventSubscriptionInstance : migratingProcessInstance.getMigratingCompensationSubscriptionInstances()) { MigratingActivityInstance ancestorInstance = migratingEventSubscriptionInstance.getClosestAncestorActivityInstance(); validateCompensateSubscriptionInstance( migratingEventSubscriptionInstance, migratingProcessInstance, migratingCompensationInstanceValidators, instanceReports.get(ancestorInstance)); } for (MigratingActivityInstanceValidationReportImpl instanceReport : instanceReports.values()) { if (instanceReport.hasFailures()) { processInstanceReport.addActivityInstanceReport(instanceReport); } } for (MigratingTransitionInstance migratingTransitionInstance : migratingProcessInstance.getMigratingTransitionInstances()) { MigratingTransitionInstanceValidationReportImpl instanceReport = validateTransitionInstance(migratingTransitionInstance, migratingProcessInstance, migratingTransitionInstanceValidators); if (instanceReport.hasFailures()) { processInstanceReport.addTransitionInstanceReport(instanceReport); } } } protected MigratingActivityInstanceValidationReportImpl validateActivityInstance(MigratingActivityInstance migratingActivityInstance, MigratingProcessInstance migratingProcessInstance, List<MigratingActivityInstanceValidator> migratingActivityInstanceValidators) { MigratingActivityInstanceValidationReportImpl instanceReport = new MigratingActivityInstanceValidationReportImpl(migratingActivityInstance); for (MigratingActivityInstanceValidator migratingActivityInstanceValidator : migratingActivityInstanceValidators) { migratingActivityInstanceValidator.validate(migratingActivityInstance, migratingProcessInstance, instanceReport); } return instanceReport; } protected MigratingTransitionInstanceValidationReportImpl validateTransitionInstance(MigratingTransitionInstance migratingTransitionInstance, MigratingProcessInstance migratingProcessInstance, List<MigratingTransitionInstanceValidator> migratingTransitionInstanceValidators) { MigratingTransitionInstanceValidationReportImpl instanceReport = new MigratingTransitionInstanceValidationReportImpl(migratingTransitionInstance); for (MigratingTransitionInstanceValidator migratingTransitionInstanceValidator : migratingTransitionInstanceValidators) { migratingTransitionInstanceValidator.validate(migratingTransitionInstance, migratingProcessInstance, instanceReport); } return instanceReport; } protected void validateEventScopeInstance(MigratingEventScopeInstance eventScopeInstance, MigratingProcessInstance migratingProcessInstance, List<MigratingCompensationInstanceValidator> migratingTransitionInstanceValidators, MigratingActivityInstanceValidationReportImpl instanceReport ) { for (MigratingCompensationInstanceValidator validator : migratingTransitionInstanceValidators) { validator.validate(eventScopeInstance, migratingProcessInstance, instanceReport); } } protected void validateCompensateSubscriptionInstance( MigratingCompensationEventSubscriptionInstance eventSubscriptionInstance, MigratingProcessInstance migratingProcessInstance, List<MigratingCompensationInstanceValidator> migratingTransitionInstanceValidators, MigratingActivityInstanceValidationReportImpl instanceReport ) { for (MigratingCompensationInstanceValidator validator : migratingTransitionInstanceValidators) { validator.validate(eventSubscriptionInstance, migratingProcessInstance, instanceReport); } } /** * Migrate activity instances to their new activities and process definition. Creates new * scope instances as necessary. */ protected void migrateProcessInstance(MigratingProcessInstance migratingProcessInstance) { MigratingActivityInstance rootActivityInstance = migratingProcessInstance.getRootInstance(); MigratingProcessElementInstanceTopDownWalker walker = new MigratingProcessElementInstanceTopDownWalker(rootActivityInstance); walker.addPreVisitor( new MigratingActivityInstanceVisitor( executionBuilder.isSkipCustomListeners(), executionBuilder.isSkipIoMappings())); walker.addPreVisitor(new MigrationCompensationInstanceVisitor()); walker.walkUntil(); } protected void ensureProcessInstanceExist(String processInstanceId, ExecutionEntity processInstance) { if (processInstance == null) { throw LOGGER.processInstanceDoesNotExist(processInstanceId); } } protected void ensureSameProcessDefinition(ExecutionEntity processInstance, String processDefinitionId) { if (!processDefinitionId.equals(processInstance.getProcessDefinitionId())) { throw LOGGER.processDefinitionOfInstanceDoesNotMatchMigrationPlan(processInstance, processDefinitionId); } } protected void ensureOperationAllowed(CommandContext commandContext, ExecutionEntity processInstance, ProcessDefinitionEntity targetProcessDefinition) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkMigrateProcessInstance(processInstance, targetProcessDefinition); } } }
xasx/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/migration/MigrateProcessInstanceCmd.java
Java
apache-2.0
17,032
class Egg{ private Yolk y; protected class Yolk{ public Yolk() { System.out.println("egg.yolk"); } } public Egg() { System.out.println("new egg"); y=new Yolk(); } } public class BigEgg extends Egg{ public class Yolk{ public Yolk() { System.out.println("Bigegg.yolk"); } } public static void main(String args[]){ new BigEgg(); } }
WuSicheng54321/Thinking-in-Java-4th
ThinkingInJava10/src/BigEgg.java
Java
apache-2.0
379
/* * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/ec2/model/ReservedInstancesListing.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::EC2::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils; ReservedInstancesListing::ReservedInstancesListing() : m_reservedInstancesListingIdHasBeenSet(false), m_reservedInstancesIdHasBeenSet(false), m_createDate(0.0), m_createDateHasBeenSet(false), m_updateDate(0.0), m_updateDateHasBeenSet(false), m_statusHasBeenSet(false), m_statusMessageHasBeenSet(false), m_instanceCountsHasBeenSet(false), m_priceSchedulesHasBeenSet(false), m_tagsHasBeenSet(false), m_clientTokenHasBeenSet(false) { } ReservedInstancesListing::ReservedInstancesListing(const XmlNode& xmlNode) : m_reservedInstancesListingIdHasBeenSet(false), m_reservedInstancesIdHasBeenSet(false), m_createDate(0.0), m_createDateHasBeenSet(false), m_updateDate(0.0), m_updateDateHasBeenSet(false), m_statusHasBeenSet(false), m_statusMessageHasBeenSet(false), m_instanceCountsHasBeenSet(false), m_priceSchedulesHasBeenSet(false), m_tagsHasBeenSet(false), m_clientTokenHasBeenSet(false) { *this = xmlNode; } ReservedInstancesListing& ReservedInstancesListing::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode reservedInstancesListingIdNode = resultNode.FirstChild("reservedInstancesListingId"); if(!reservedInstancesListingIdNode.IsNull()) { m_reservedInstancesListingId = StringUtils::Trim(reservedInstancesListingIdNode.GetText().c_str()); m_reservedInstancesListingIdHasBeenSet = true; } XmlNode reservedInstancesIdNode = resultNode.FirstChild("reservedInstancesId"); if(!reservedInstancesIdNode.IsNull()) { m_reservedInstancesId = StringUtils::Trim(reservedInstancesIdNode.GetText().c_str()); m_reservedInstancesIdHasBeenSet = true; } XmlNode createDateNode = resultNode.FirstChild("createDate"); if(!createDateNode.IsNull()) { m_createDate = StringUtils::ConvertToDouble(StringUtils::Trim(createDateNode.GetText().c_str()).c_str()); m_createDateHasBeenSet = true; } XmlNode updateDateNode = resultNode.FirstChild("updateDate"); if(!updateDateNode.IsNull()) { m_updateDate = StringUtils::ConvertToDouble(StringUtils::Trim(updateDateNode.GetText().c_str()).c_str()); m_updateDateHasBeenSet = true; } XmlNode statusNode = resultNode.FirstChild("status"); if(!statusNode.IsNull()) { m_status = ListingStatusMapper::GetListingStatusForName(StringUtils::Trim(statusNode.GetText().c_str()).c_str()); m_statusHasBeenSet = true; } XmlNode statusMessageNode = resultNode.FirstChild("statusMessage"); if(!statusMessageNode.IsNull()) { m_statusMessage = StringUtils::Trim(statusMessageNode.GetText().c_str()); m_statusMessageHasBeenSet = true; } XmlNode instanceCountsNode = resultNode.FirstChild("instanceCounts"); if(!instanceCountsNode.IsNull()) { XmlNode instanceCountsMember = instanceCountsNode.FirstChild("item"); while(!instanceCountsMember.IsNull()) { m_instanceCounts.push_back(instanceCountsMember); instanceCountsMember = instanceCountsMember.NextNode("item"); } m_instanceCountsHasBeenSet = true; } XmlNode priceSchedulesNode = resultNode.FirstChild("priceSchedules"); if(!priceSchedulesNode.IsNull()) { XmlNode priceSchedulesMember = priceSchedulesNode.FirstChild("item"); while(!priceSchedulesMember.IsNull()) { m_priceSchedules.push_back(priceSchedulesMember); priceSchedulesMember = priceSchedulesMember.NextNode("item"); } m_priceSchedulesHasBeenSet = true; } XmlNode tagsNode = resultNode.FirstChild("tagSet"); if(!tagsNode.IsNull()) { XmlNode tagsMember = tagsNode.FirstChild("item"); while(!tagsMember.IsNull()) { m_tags.push_back(tagsMember); tagsMember = tagsMember.NextNode("item"); } m_tagsHasBeenSet = true; } XmlNode clientTokenNode = resultNode.FirstChild("clientToken"); if(!clientTokenNode.IsNull()) { m_clientToken = StringUtils::Trim(clientTokenNode.GetText().c_str()); m_clientTokenHasBeenSet = true; } } return *this; } void ReservedInstancesListing::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_reservedInstancesListingIdHasBeenSet) { oStream << location << index << locationValue << ".ReservedInstancesListingId=" << StringUtils::URLEncode(m_reservedInstancesListingId.c_str()) << "&"; } if(m_reservedInstancesIdHasBeenSet) { oStream << location << index << locationValue << ".ReservedInstancesId=" << StringUtils::URLEncode(m_reservedInstancesId.c_str()) << "&"; } if(m_createDateHasBeenSet) { oStream << location << index << locationValue << ".CreateDate=" << m_createDate << "&"; } if(m_updateDateHasBeenSet) { oStream << location << index << locationValue << ".UpdateDate=" << m_updateDate << "&"; } if(m_statusHasBeenSet) { oStream << location << index << locationValue << ".Status=" << ListingStatusMapper::GetNameForListingStatus(m_status) << "&"; } if(m_statusMessageHasBeenSet) { oStream << location << index << locationValue << ".StatusMessage=" << StringUtils::URLEncode(m_statusMessage.c_str()) << "&"; } if(m_instanceCountsHasBeenSet) { unsigned instanceCountsIdx = 0; for(auto& item : m_instanceCounts) { instanceCountsIdx++; Aws::StringStream instanceCountsSs; instanceCountsSs << location << index << locationValue << ".InstanceCounts." << instanceCountsIdx; item.OutputToStream(oStream, instanceCountsSs.str().c_str()); } } if(m_priceSchedulesHasBeenSet) { unsigned priceSchedulesIdx = 0; for(auto& item : m_priceSchedules) { priceSchedulesIdx++; Aws::StringStream priceSchedulesSs; priceSchedulesSs << location << index << locationValue << ".PriceSchedules." << priceSchedulesIdx; item.OutputToStream(oStream, priceSchedulesSs.str().c_str()); } } if(m_tagsHasBeenSet) { unsigned tagsIdx = 0; for(auto& item : m_tags) { tagsIdx++; Aws::StringStream tagsSs; tagsSs << location << index << locationValue << ".TagSet." << tagsIdx; item.OutputToStream(oStream, tagsSs.str().c_str()); } } if(m_clientTokenHasBeenSet) { oStream << location << index << locationValue << ".ClientToken=" << StringUtils::URLEncode(m_clientToken.c_str()) << "&"; } } void ReservedInstancesListing::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_reservedInstancesListingIdHasBeenSet) { oStream << location << ".ReservedInstancesListingId=" << StringUtils::URLEncode(m_reservedInstancesListingId.c_str()) << "&"; } if(m_reservedInstancesIdHasBeenSet) { oStream << location << ".ReservedInstancesId=" << StringUtils::URLEncode(m_reservedInstancesId.c_str()) << "&"; } if(m_createDateHasBeenSet) { oStream << location << ".CreateDate=" << m_createDate << "&"; } if(m_updateDateHasBeenSet) { oStream << location << ".UpdateDate=" << m_updateDate << "&"; } if(m_statusHasBeenSet) { oStream << location << ".Status=" << ListingStatusMapper::GetNameForListingStatus(m_status) << "&"; } if(m_statusMessageHasBeenSet) { oStream << location << ".StatusMessage=" << StringUtils::URLEncode(m_statusMessage.c_str()) << "&"; } if(m_instanceCountsHasBeenSet) { for(auto& item : m_instanceCounts) { Aws::String locationAndListMember(location); locationAndListMember += ".item"; item.OutputToStream(oStream, locationAndListMember.c_str()); } } if(m_priceSchedulesHasBeenSet) { for(auto& item : m_priceSchedules) { Aws::String locationAndListMember(location); locationAndListMember += ".item"; item.OutputToStream(oStream, locationAndListMember.c_str()); } } if(m_tagsHasBeenSet) { for(auto& item : m_tags) { Aws::String locationAndListMember(location); locationAndListMember += ".item"; item.OutputToStream(oStream, locationAndListMember.c_str()); } } if(m_clientTokenHasBeenSet) { oStream << location << ".ClientToken=" << StringUtils::URLEncode(m_clientToken.c_str()) << "&"; } }
kahkeng/aws-sdk-cpp
aws-cpp-sdk-ec2/source/model/ReservedInstancesListing.cpp
C++
apache-2.0
9,310
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DynamicLinqWithExpressionTree")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DynamicLinqWithExpressionTree")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c82e9e14-a854-485f-8b27-d3fbb6a87f00")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
anbinhtrong/DynamicLinQWithExpressionTree
DynamicLinqWithExpressionTree/Properties/AssemblyInfo.cs
C#
apache-2.0
1,434
namespace RAML.Parser { public enum SpecificationType { RAML, RAML08, OASJSON, OASYAML, OAS3JSON, OAS3YAML } }
raml-org/raml-dotnet-parser
source/RAML.Parser/SpecificationType.cs
C#
apache-2.0
173
# frozen_string_literal: true def windows_facts { 'docker_program_data_path' => 'C:/ProgramData', 'docker_program_files_path' => 'C:/Program Files', 'docker_systemroot' => 'C:/Windows', 'docker_user_temp_path' => 'C:/Users/Administrator/AppData/Local/Temp', } end
puppetlabs/puppetlabs-docker
spec/helper/windows_facts.rb
Ruby
apache-2.0
298
package uk.ac.ebi.quickgo.rest.search.query; import com.google.common.base.Preconditions; /** * A simple abstract field representation. * * Created 11/02/16 * @author Edd */ public abstract class AbstractField implements Field { protected String field; public AbstractField(String field) { Preconditions.checkArgument(field != null && field.length() > 0, "Field cannot be null or empty"); this.field = field; } public String getField() { return field; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractField that = (AbstractField) o; return field != null ? field.equals(that.field) : that.field == null; } @Override public int hashCode() { return field != null ? field.hashCode() : 0; } @Override public String toString() { return "AbstractField{" + "field='" + field + '\'' + '}'; } }
ebi-uniprot/QuickGOBE
rest-common/src/main/java/uk/ac/ebi/quickgo/rest/search/query/AbstractField.java
Java
apache-2.0
1,089
<?php class numbers_data_accounting_gl_model_list_setting_source_codes extends numbers_frontend_html_list_base { public $list_link = 'source_codes'; public $model = 'numbers_data_accounting_gl_model_setting_source_codes'; public $columns = [ 'offset_number' => ['name' => '&nbsp;', 'width' => '1%', 'align' => 'right'], 'action' => ['name' => 'Action', 'width' => '1%'], 'gl_source_ledger_code' => ['name' => 'Ledger', 'domain' => 'ledger_code', 'options_model' => 'numbers_data_accounting_cs_model_ledgers'], 'gl_source_code' => ['name' => 'Source Code', 'domain' => 'source_code'], 'gl_source_name' => ['name' => 'Name', 'domain' => 'name'], 'gl_source_inactive' => ['name' => 'Inactive', 'type' => 'boolean', 'options_model' => 'object_data_model_inactive'] ]; public $filter = [ 'gl_source_ledger_code' => ['name' => 'Ledger', 'domain' => 'ledger_code', 'method' => 'html::multiselect', 'options_model' => 'numbers_data_accounting_cs_model_ledgers'], 'gl_source_code' => ['name' => 'Source Code', 'domain' => 'source_code'], 'gl_source_name' => ['name' => 'Name', 'domain' => 'name'], 'gl_source_inactive' => ['name' => 'Inactive', 'type' => 'boolean', 'method' => 'html::multiselect', 'options_model' => 'object_data_model_inactive'], 'full_text_search' => ['gl_source_ledger_code', 'gl_source_code', 'gl_source_name'] ]; public $orderby = [ 'gl_source_ledger_code' => SORT_ASC, 'gl_source_code' => SORT_ASC ]; public $datasources = [ 'count' => null, 'data' => null ]; public $pagination = [ 'top' => 'numbers_frontend_html_list_pagination_base', 'bottom' => 'numbers_frontend_html_list_pagination_base' ]; }
volodymyr-volynets/data
accounting/gl/model/list/setting/source/codes.php
PHP
apache-2.0
1,661
<?php use Phinx\Migration\AbstractMigration; class InitDb extends AbstractMigration { /** * Migrate Up. */ public function up() { $this->query("CREATE TABLE `suggestions_types` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `type` varchar(32) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `type` (`type`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); $this->query("CREATE TABLE `suggestions` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `type_id` int(11) unsigned NOT NULL DEFAULT '0', `content` text, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `type_id` (`type_id`), CONSTRAINT `suggestions_ibfk_1` FOREIGN KEY (`type_id`) REFERENCES `suggestions_types` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"); } /** * Migrate Down. */ public function down() { $this->query("DROP TABLE `suggestions`"); $this->query("DROP TABLE `suggestions_types`"); } }
GreaterLaLa/greaterlala.in
app/migrations/20140329195744_init_db.php
PHP
apache-2.0
1,309
<?php /** * Created by PhpStorm. * User: james * Date: 2017/10/26 * Time: 21:56 */ namespace app\admin\validate; class GradeValidate extends BaseValidate { protected $rule = [ 'grade' => 'require|number' ]; protected $message = [ 'grade.number' => '参数不合法', 'grade.require' => '缺少参数' ]; }
jamesXG/luoyang
application/admin/validate/GradeValidate.php
PHP
apache-2.0
345
/** * Methods to export/dump the current de-normalised table model as flat table. */ package org.eu.eark.denormalizedb.dump; // TODO implement various dumps like CSV, HBase // load into HBase as one table per exploded table // later load into Lily as one Record type
eark-project/denormalize-db
src/main/java/org/eu/eark/denormalizedb/dump/package-info.java
Java
apache-2.0
270
package com.xieyu.study.autoconfigure; import org.hornetq.core.config.Configuration; public interface HornetQConfigurationCustomizer { void customize(Configuration configuration); }
xieyufish/note
代码/autoconfigure/study-spring-boot-autoconfigure/src/main/java/com/xieyu/study/autoconfigure/HornetQConfigurationCustomizer.java
Java
apache-2.0
189
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cli.net; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onosproject.net.Device; import org.onosproject.net.Host; import org.onosproject.net.Link; import org.onosproject.net.device.DeviceAdminService; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.group.GroupService; import org.onosproject.net.host.HostAdminService; import org.onosproject.net.intent.Intent; import org.onosproject.net.intent.IntentService; import org.onosproject.net.intent.IntentState; import org.onosproject.net.link.LinkAdminService; import org.onosproject.net.region.RegionAdminService; import org.onosproject.ui.UiTopoLayoutService; import java.util.EnumSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.onosproject.net.intent.IntentState.FAILED; import static org.onosproject.net.intent.IntentState.WITHDRAWN; /** * Wipes-out the entire network information base, i.e. devices, links, hosts, intents. */ @Command(scope = "onos", name = "wipe-out", description = "Wipes-out the entire network information base, i.e. devices, links, hosts") public class WipeOutCommand extends ClustersListCommand { private static final String PLEASE = "please"; private static final EnumSet<IntentState> CAN_PURGE = EnumSet.of(WITHDRAWN, FAILED); @Argument(index = 0, name = "please", description = "Confirmation phrase", required = false, multiValued = false) String please = null; @Override protected void execute() { if (please == null || !please.equals(PLEASE)) { print("I'm afraid I can't do that!\nSay: %s", PLEASE); return; } wipeOutIntents(); wipeOutHosts(); wipeOutFlows(); wipeOutGroups(); wipeOutDevices(); wipeOutLinks(); wipeOutLayouts(); wipeOutRegions(); } private void wipeOutIntents() { print("Wiping intents"); IntentService intentService = get(IntentService.class); final CountDownLatch withdrawLatch; withdrawLatch = new CountDownLatch(1); for (Intent intent : intentService.getIntents()) { if (intentService.getIntentState(intent.key()) != IntentState.WITHDRAWN) { intentService.withdraw(intent); try { // wait for withdraw event withdrawLatch.await(5, TimeUnit.SECONDS); } catch (InterruptedException e) { print("Timed out waiting for intent {} withdraw"); } } if (CAN_PURGE.contains(intentService.getIntentState(intent.key()))) { intentService.purge(intent); } } } private void wipeOutFlows() { print("Wiping Flows"); FlowRuleService flowRuleService = get(FlowRuleService.class); DeviceAdminService deviceAdminService = get(DeviceAdminService.class); for (Device device : deviceAdminService.getDevices()) { flowRuleService.purgeFlowRules(device.id()); } } private void wipeOutGroups() { print("Wiping groups"); GroupService groupService = get(GroupService.class); DeviceAdminService deviceAdminService = get(DeviceAdminService.class); for (Device device : deviceAdminService.getDevices()) { groupService.purgeGroupEntries(device.id()); } } private void wipeOutHosts() { print("Wiping hosts"); HostAdminService hostAdminService = get(HostAdminService.class); while (hostAdminService.getHostCount() > 0) { try { for (Host host : hostAdminService.getHosts()) { hostAdminService.removeHost(host.id()); } } catch (Exception e) { log.info("Unable to wipe-out hosts", e); } } } private void wipeOutDevices() { print("Wiping devices"); DeviceAdminService deviceAdminService = get(DeviceAdminService.class); while (deviceAdminService.getDeviceCount() > 0) { try { for (Device device : deviceAdminService.getDevices()) { deviceAdminService.removeDevice(device.id()); } } catch (Exception e) { log.info("Unable to wipe-out devices", e); } } } private void wipeOutLinks() { print("Wiping links"); LinkAdminService linkAdminService = get(LinkAdminService.class); while (linkAdminService.getLinkCount() > 0) { try { for (Link link : linkAdminService.getLinks()) { linkAdminService.removeLinks(link.src()); linkAdminService.removeLinks(link.dst()); } } catch (Exception e) { log.info("Unable to wipe-out links", e); } } } private void wipeOutLayouts() { print("Wiping UI layouts"); UiTopoLayoutService service = get(UiTopoLayoutService.class); // wipe out all layouts except the default, which should always be there service.getLayouts().forEach(l -> { if (!l.id().isDefault()) { service.removeLayout(l); } }); } private void wipeOutRegions() { print("Wiping regions"); RegionAdminService service = get(RegionAdminService.class); service.getRegions().forEach(r -> service.removeRegion(r.id())); } }
sdnwiselab/onos
cli/src/main/java/org/onosproject/cli/net/WipeOutCommand.java
Java
apache-2.0
6,233
package de.hpi.bpmn.serialization.erdf.templates; import de.hpi.bpmn.DiagramObject; import de.hpi.bpmn.EndMultipleEvent; import de.hpi.bpmn.serialization.erdf.ERDFSerializationContext; public class EndMultipleEventTemplate extends NonConnectorTemplate { private static BPMN2ERDFTemplate instance; public static BPMN2ERDFTemplate getInstance() { if (instance == null) { instance = new EndPlainEventTemplate(); } return instance; } public StringBuilder getCompletedTemplate(DiagramObject diagramObject, ERDFSerializationContext transformationContext) { EndMultipleEvent e = (EndMultipleEvent) diagramObject; StringBuilder s = getResourceStartPattern(transformationContext.getResourceIDForDiagramObject(e)); appendOryxField(s,"type",STENCIL_URI + "#EndMultipleEvent"); appendOryxField(s,"eventtype","End"); appendNonConnectorStandardFields(e,s,transformationContext); appendOryxField(s,"result","Multiple"); appendResourceEndPattern(s, e, transformationContext); return s; } }
grasscrm/gdesigner
editor/server/src/de/hpi/bpmn/serialization/erdf/templates/EndMultipleEventTemplate.java
Java
apache-2.0
1,020
package com.ucar.weex.commons.adapter; import com.taobao.weex.adapter.IWXJSExceptionAdapter; import com.taobao.weex.common.WXJSExceptionInfo; /** * Created by chenxi.cui on 2017/7/27. */ public class JSExceptionAdapter implements IWXJSExceptionAdapter { @Override public void onJSException(WXJSExceptionInfo exception) { // UWLog.v(exception.getException()); } }
weexext/ucar-weex-core
platforms/android/uwx/src/main/java/com/ucar/weex/commons/adapter/JSExceptionAdapter.java
Java
apache-2.0
387
package com.github.romankh3.image.comparison; import com.github.romankh3.image.comparison.model.ExcludedAreas; import com.github.romankh3.image.comparison.model.ImageComparisonResult; import com.github.romankh3.image.comparison.model.ImageComparisonState; import com.github.romankh3.image.comparison.model.Rectangle; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import java.util.*; import java.util.stream.Collectors; import static com.github.romankh3.image.comparison.ImageComparisonUtil.getDifferencePercent; import static java.util.Collections.emptyList; /** * Main class for comparison images. */ public class ImageComparison { /** * The threshold which means the max distance between non-equal pixels. * Could be changed according to the size and requirements of the image. */ private int threshold = 5; /** * Expected image for comparison */ private final BufferedImage expected; /** * Actual image for comparison */ private final BufferedImage actual; /** * Width of the line that is drawn the rectangle */ private int rectangleLineWidth = 1; /** * {@link File} of the result destination. */ private /* @Nullable */ File destination; /** * The number which marks how many rectangles. Beginning from 2. */ private int counter = 2; /** * The number of the marking specific rectangle. */ private int regionCount = counter; /** * The number of the minimal rectangle size. Count as (width x height). */ private Integer minimalRectangleSize = 1; /** * Maximal count of the {@link Rectangle}s. * It means that would get the first x biggest rectangles. * Default value is -1, that means that all the rectangles would be drawn. */ private Integer maximalRectangleCount = -1; /** * Level of the pixel tolerance. By default, it's 0.1 -> 10% difference. * The value can be set from 0.0 to 0.99. */ private double pixelToleranceLevel = 0.1; /** * Constant using for counting the level of the difference. */ private double differenceConstant; /** * Matrix YxX => int[y][x]. * E.g.: * | X - width ---- * | ..................................... * Y . (0, 0) . * | . . * | . . * h . . * e . . * i . . * g . . * h . . * t . (X, Y). * | ..................................... */ private int[][] matrix; /** * ExcludedAreas contains a List of {@link Rectangle}s to be ignored when comparing images */ private ExcludedAreas excludedAreas = new ExcludedAreas(); /** * Flag which says draw excluded rectangles or not. */ private boolean drawExcludedRectangles = false; /** * The difference in percent between two images. */ private float differencePercent; /** * Flag for filling comparison difference rectangles. */ private boolean fillDifferenceRectangles = false; /** * Sets the opacity percentage of the fill of comparison difference rectangles. 0.0 means completely transparent and 100.0 means completely opaque. */ private double percentOpacityDifferenceRectangles = 20.0; /** * Flag for filling excluded rectangles. */ private boolean fillExcludedRectangles = false; /** * Sets the opacity percentage of the fill of excluded rectangles. 0.0 means completely transparent and 100.0 means completely opaque. */ private double percentOpacityExcludedRectangles = 20.0; /** * The percent of the allowing pixels to be different to stay {@link ImageComparisonState#MATCH} for comparison. * E.g. percent of the pixels, which would ignore in comparison. */ private double allowingPercentOfDifferentPixels = 0.0; /** * Sets rectangle color of image difference. By default, it's red. */ private Color differenceRectangleColor = Color.RED; /** * Sets rectangle color of excluded part. By default, it's green. */ private Color excludedRectangleColor = Color.GREEN; /** * Create a new instance of {@link ImageComparison} that can compare the given images. * * @param expected expected image to be compared * @param actual actual image to be compared */ public ImageComparison(String expected, String actual) { this(ImageComparisonUtil.readImageFromResources(expected), ImageComparisonUtil.readImageFromResources(actual), null); } /** * Create a new instance of {@link ImageComparison} that can compare the given images. * * @param expected expected image to be compared * @param actual actual image to be compared * @param destination destination to save the result. If null, the result is shown in the UI. */ public ImageComparison(BufferedImage expected, BufferedImage actual, File destination) { this.expected = expected; this.actual = actual; this.destination = destination; differenceConstant = calculateDifferenceConstant(); } /** * Create a new instance of {@link ImageComparison} that can compare the given images. * * @param expected expected image to be compared * @param actual actual image to be compared */ public ImageComparison(BufferedImage expected, BufferedImage actual) { this(expected, actual, null); } /** * Draw rectangles which cover the regions of the difference pixels. * * @return the result of the drawing. */ public ImageComparisonResult compareImages() { // check that the images have the same size if (isImageSizesNotEqual(expected, actual)) { BufferedImage actualResized = ImageComparisonUtil.resize(actual, expected.getWidth(), expected.getHeight()); return ImageComparisonResult.defaultSizeMisMatchResult(expected, actual, getDifferencePercent(actualResized, expected)); } List<Rectangle> rectangles = populateRectangles(); if (rectangles.isEmpty()) { ImageComparisonResult matchResult = ImageComparisonResult.defaultMatchResult(expected, actual); if (drawExcludedRectangles) { matchResult.setResult(drawRectangles(rectangles)); saveImageForDestination(matchResult.getResult()); } return matchResult; } BufferedImage resultImage = drawRectangles(rectangles); saveImageForDestination(resultImage); return ImageComparisonResult.defaultMisMatchResult(expected, actual, getDifferencePercent(actual, expected)) .setResult(resultImage) .setRectangles(rectangles); } /** * Check images for equals their widths and heights. * * @param expected {@link BufferedImage} object of the expected image. * @param actual {@link BufferedImage} object of the actual image. * @return true if image size are not equal, false otherwise. */ private boolean isImageSizesNotEqual(BufferedImage expected, BufferedImage actual) { return expected.getHeight() != actual.getHeight() || expected.getWidth() != actual.getWidth(); } /** * Populate binary matrix with "0" and "1". If the pixels are different set it as "1", otherwise "0". * * @return the count of different pixels */ private long populateTheMatrixOfTheDifferences() { long countOfDifferentPixels = 0; matrix = new int[expected.getHeight()][expected.getWidth()]; for (int y = 0; y < expected.getHeight(); y++) { for (int x = 0; x < expected.getWidth(); x++) { if (!excludedAreas.contains(new Point(x, y))) { if (isDifferentPixels(expected.getRGB(x, y), actual.getRGB(x, y))) { matrix[y][x] = 1; countOfDifferentPixels++; } } } } return countOfDifferentPixels; } /** * Say if the two pixels equal or not. The rule is the difference between two pixels * need to be more than {@link #pixelToleranceLevel}. * * @param expectedRgb the RGB value of the Pixel of the Expected image. * @param actualRgb the RGB value of the Pixel of the Actual image. * @return {@code true} if they' are difference, {@code false} otherwise. */ private boolean isDifferentPixels(int expectedRgb, int actualRgb) { if (expectedRgb == actualRgb) { return false; } else if (pixelToleranceLevel == 0.0) { return true; } int red1 = (expectedRgb >> 16) & 0xff; int green1 = (expectedRgb >> 8) & 0xff; int blue1 = (expectedRgb) & 0xff; int red2 = (actualRgb >> 16) & 0xff; int green2 = (actualRgb >> 8) & 0xff; int blue2 = (actualRgb) & 0xff; return (Math.pow(red2 - red1, 2) + Math.pow(green2 - green1, 2) + Math.pow(blue2 - blue1, 2)) > differenceConstant; } /** * Populate rectangles of the differences * * @return the collection of the populated {@link Rectangle} objects. */ private List<Rectangle> populateRectangles() { long countOfDifferentPixels = populateTheMatrixOfTheDifferences(); if (countOfDifferentPixels == 0) { return emptyList(); } if (isAllowedPercentOfDifferentPixels(countOfDifferentPixels)) { return emptyList(); } groupRegions(); List<Rectangle> rectangles = new ArrayList<>(); while (counter <= regionCount) { Rectangle rectangle = createRectangle(); if (!rectangle.equals(Rectangle.createDefault()) && rectangle.size() >= minimalRectangleSize) { rectangles.add(rectangle); } counter++; } return mergeRectangles(mergeRectangles(rectangles)); } /** * Say if provided {@param countOfDifferentPixels} is allowed for {@link ImageComparisonState#MATCH} state. * * @param countOfDifferentPixels the count of the different pixels in comparison. * @return true, if percent of different pixels lower or equal {@link ImageComparison#allowingPercentOfDifferentPixels}, * false - otherwise. */ private boolean isAllowedPercentOfDifferentPixels(long countOfDifferentPixels) { long totalPixelCount = matrix.length * matrix[0].length; double actualPercentOfDifferentPixels = ((double) countOfDifferentPixels / (double) totalPixelCount) * 100; return actualPercentOfDifferentPixels <= allowingPercentOfDifferentPixels; } /** * Create a {@link Rectangle} object. * * @return the {@link Rectangle} object. */ private Rectangle createRectangle() { Rectangle rectangle = Rectangle.createDefault(); for (int y = 0; y < matrix.length; y++) { for (int x = 0; x < matrix[0].length; x++) { if (matrix[y][x] == counter) { updateRectangleCreation(rectangle, x, y); } } } return rectangle; } /** * Update {@link Point} of the rectangle based on x and y coordinates. */ private void updateRectangleCreation(Rectangle rectangle, int x, int y) { if (x < rectangle.getMinPoint().getX()) { rectangle.getMinPoint().x = x; } if (x > rectangle.getMaxPoint().getX()) { rectangle.getMaxPoint().x = x; } if (y < rectangle.getMinPoint().getY()) { rectangle.getMinPoint().y = y; } if (y > rectangle.getMaxPoint().getY()) { rectangle.getMaxPoint().y = y; } } /** * Find overlapping rectangles and merge them. */ private List<Rectangle> mergeRectangles(List<Rectangle> rectangles) { int position = 0; while (position < rectangles.size()) { if (rectangles.get(position).equals(Rectangle.createZero())) { position++; } for (int i = 1 + position; i < rectangles.size(); i++) { Rectangle r1 = rectangles.get(position); Rectangle r2 = rectangles.get(i); if (r2.equals(Rectangle.createZero())) { continue; } if (r1.isOverlapping(r2)) { rectangles.set(position, r1.merge(r2)); r2.makeZeroRectangle(); if (position != 0) { position--; } } } position++; } return rectangles.stream().filter(it -> !it.equals(Rectangle.createZero())).collect(Collectors.toList()); } /** * Draw the rectangles based on collection of the rectangles and result image. * * @param rectangles the collection of the {@link Rectangle} objects. * @return result {@link BufferedImage} with drawn rectangles. */ private BufferedImage drawRectangles(List<Rectangle> rectangles) { BufferedImage resultImage = ImageComparisonUtil.deepCopy(actual); Graphics2D graphics = preparedGraphics2D(resultImage); drawExcludedRectangles(graphics); drawRectanglesOfDifferences(rectangles, graphics); return resultImage; } /** * Draw excluded rectangles. * * @param graphics prepared {@link Graphics2D}object. */ private void drawExcludedRectangles(Graphics2D graphics) { if (drawExcludedRectangles) { graphics.setColor(this.excludedRectangleColor); draw(graphics, excludedAreas.getExcluded()); if (fillExcludedRectangles) { fillRectangles(graphics, excludedAreas.getExcluded(), percentOpacityExcludedRectangles); } } } /** * Draw rectangles with the differences. * * @param rectangles the collection of the {@link Rectangle} of differences. * @param graphics prepared {@link Graphics2D}object. */ private void drawRectanglesOfDifferences(List<Rectangle> rectangles, Graphics2D graphics) { List<Rectangle> rectanglesForDraw; graphics.setColor(this.differenceRectangleColor); if (maximalRectangleCount > 0 && maximalRectangleCount < rectangles.size()) { rectanglesForDraw = rectangles.stream() .sorted(Comparator.comparing(Rectangle::size)) .skip(rectangles.size() - maximalRectangleCount) .collect(Collectors.toList()); } else { rectanglesForDraw = new ArrayList<>(rectangles); } draw(graphics, rectanglesForDraw); if (fillDifferenceRectangles) { fillRectangles(graphics, rectanglesForDraw, percentOpacityDifferenceRectangles); } } /** * Prepare {@link Graphics2D} based on resultImage and rectangleLineWidth * * @param image image based on created {@link Graphics2D}. * @return prepared {@link Graphics2D} object. */ private Graphics2D preparedGraphics2D(BufferedImage image) { Graphics2D graphics = image.createGraphics(); graphics.setStroke(new BasicStroke(rectangleLineWidth)); return graphics; } /** * Save image to destination object if exists. * * @param image {@link BufferedImage} to be saved. */ private void saveImageForDestination(BufferedImage image) { if (Objects.nonNull(destination)) { ImageComparisonUtil.saveImage(destination, image); } } /** * Draw rectangles based on collection of the {@link Rectangle} and {@link Graphics2D}. * getWidth/getHeight return real width/height, * so need to draw rectangle on one px smaller because minpoint + width/height is point on excluded pixel. * * @param graphics the {@link Graphics2D} object for drawing. * @param rectangles the collection of the {@link Rectangle}. */ private void draw(Graphics2D graphics, List<Rectangle> rectangles) { rectangles.forEach(rectangle -> graphics.drawRect( rectangle.getMinPoint().x, rectangle.getMinPoint().y, rectangle.getWidth() - 1, rectangle.getHeight() - 1) ); } /** * Fill rectangles based on collection of the {@link Rectangle} and {@link Graphics2D}. * getWidth/getHeight return real width/height, * so need to draw rectangle fill two px smaller to fit inside rectangle borders. * * @param graphics the {@link Graphics2D} object for drawing. * @param rectangles rectangles the collection of the {@link Rectangle}. * @param percentOpacity the opacity of the fill. */ private void fillRectangles(Graphics2D graphics, List<Rectangle> rectangles, double percentOpacity) { graphics.setColor(new Color(graphics.getColor().getRed(), graphics.getColor().getGreen(), graphics.getColor().getBlue(), (int) (percentOpacity / 100 * 255) )); rectangles.forEach(rectangle -> graphics.fillRect( rectangle.getMinPoint().x - 1, rectangle.getMinPoint().y - 1, rectangle.getWidth() - 2, rectangle.getHeight() - 2) ); } /** * Group rectangle regions in matrix. */ private void groupRegions() { for (int y = 0; y < matrix.length; y++) { for (int x = 0; x < matrix[y].length; x++) { if (matrix[y][x] == 1) { joinToRegion(x, y); regionCount++; } } } } /** * The recursive method which go to all directions and finds difference * in binary matrix using {@code threshold} for setting max distance between values which equal "1". * and set the {@code groupCount} to matrix. * * @param x the value of the X-coordinate. * @param y the value of the Y-coordinate. */ private void joinToRegion(int x, int y) { if (isJumpRejected(x, y)) { return; } matrix[y][x] = regionCount; for (int i = 0; i < threshold; i++) { joinToRegion(x + 1 + i, y); joinToRegion(x, y + 1 + i); joinToRegion(x + 1 + i, y - 1 - i); joinToRegion(x - 1 - i, y + 1 + i); joinToRegion(x + 1 + i, y + 1 + i); } } /** * Returns the list of rectangles that would be drawn as a diff image. * If you submit two images that are the same barring the parts you want to excludedAreas you get a list of * rectangles that can be used as said excludedAreas * * @return List of {@link Rectangle} */ public List<Rectangle> createMask() { return populateRectangles(); } /** * Check next step valid or not. * * @param x X-coordinate of the image. * @param y Y-coordinate of the image * @return true if jump rejected, otherwise false. */ private boolean isJumpRejected(int x, int y) { return y < 0 || y >= matrix.length || x < 0 || x >= matrix[y].length || matrix[y][x] != 1; } public double getPixelToleranceLevel() { return pixelToleranceLevel; } public ImageComparison setPixelToleranceLevel(double pixelToleranceLevel) { if (0.0 <= pixelToleranceLevel && pixelToleranceLevel < 1) { this.pixelToleranceLevel = pixelToleranceLevel; differenceConstant = calculateDifferenceConstant(); } return this; } private double calculateDifferenceConstant() { return Math.pow(pixelToleranceLevel * Math.sqrt(Math.pow(255, 2) * 3), 2); } public boolean isDrawExcludedRectangles() { return drawExcludedRectangles; } public ImageComparison setDrawExcludedRectangles(boolean drawExcludedRectangles) { this.drawExcludedRectangles = drawExcludedRectangles; return this; } public int getThreshold() { return threshold; } public ImageComparison setThreshold(int threshold) { this.threshold = threshold; return this; } public Optional<File> getDestination() { return Optional.ofNullable(destination); } public ImageComparison setDestination(File destination) { this.destination = destination; return this; } public BufferedImage getExpected() { return expected; } public BufferedImage getActual() { return actual; } public int getRectangleLineWidth() { return rectangleLineWidth; } public ImageComparison setRectangleLineWidth(int rectangleLineWidth) { this.rectangleLineWidth = rectangleLineWidth; return this; } public Integer getMinimalRectangleSize() { return minimalRectangleSize; } public ImageComparison setMinimalRectangleSize(Integer minimalRectangleSize) { this.minimalRectangleSize = minimalRectangleSize; return this; } public Integer getMaximalRectangleCount() { return maximalRectangleCount; } public ImageComparison setMaximalRectangleCount(Integer maximalRectangleCount) { this.maximalRectangleCount = maximalRectangleCount; return this; } public ImageComparison setExcludedAreas(List<Rectangle> excludedAreas) { this.excludedAreas = new ExcludedAreas(excludedAreas); return this; } public boolean isFillDifferenceRectangles() { return this.fillDifferenceRectangles; } public double getPercentOpacityDifferenceRectangles() { return this.percentOpacityDifferenceRectangles; } public ImageComparison setDifferenceRectangleFilling(boolean fillRectangles, double percentOpacity) { this.fillDifferenceRectangles = fillRectangles; this.percentOpacityDifferenceRectangles = percentOpacity; return this; } public boolean isFillExcludedRectangles() { return this.fillExcludedRectangles; } public double getPercentOpacityExcludedRectangles() { return this.percentOpacityExcludedRectangles; } public ImageComparison setExcludedRectangleFilling(boolean fillRectangles, double percentOpacity) { this.fillExcludedRectangles = fillRectangles; this.percentOpacityExcludedRectangles = percentOpacity; return this; } public double getAllowingPercentOfDifferentPixels() { return allowingPercentOfDifferentPixels; } public ImageComparison setAllowingPercentOfDifferentPixels(double allowingPercentOfDifferentPixels) { if (0.0 <= allowingPercentOfDifferentPixels && allowingPercentOfDifferentPixels <= 100) { this.allowingPercentOfDifferentPixels = allowingPercentOfDifferentPixels; } else { //todo add warning here } return this; } public Color getDifferenceRectangleColor() { return this.differenceRectangleColor; } public ImageComparison setDifferenceRectangleColor(Color differenceRectangleColor) { this.differenceRectangleColor = differenceRectangleColor; return this; } public Color getExcludedRectangleColor() { return this.excludedRectangleColor; } public ImageComparison setExcludedRectangleColor(Color excludedRectangleColor) { this.excludedRectangleColor = excludedRectangleColor; return this; } }
romankh3/image-comparison
src/main/java/com/github/romankh3/image/comparison/ImageComparison.java
Java
apache-2.0
24,161
/* * Copyright 2009-2016 European Molecular Biology Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ebi.fg.annotare2.db.model; import com.google.common.base.Optional; import org.junit.Test; import uk.ac.ebi.fg.annotare2.db.model.enums.Permission; import uk.ac.ebi.fg.annotare2.db.model.enums.Role; import java.util.Collection; import static java.util.Arrays.asList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author Olga Melnichuk */ public class EffectiveAclTest { private long id = 0; @Test public void testEffectiveAclHasPermission() { Acl acl = new Acl(); acl.getEntries().addAll( asList(new AclEntry(Role.AUTHENTICATED, Permission.CREATE), new AclEntry(Role.CREATOR, Permission.VIEW), new AclEntry(Role.OWNER, Permission.VIEW), new AclEntry(Role.OWNER, Permission.UPDATE))); User creator = createUser(asList(Role.AUTHENTICATED)); User owner = createUser(asList(Role.AUTHENTICATED)); User other = createUser(asList(Role.AUTHENTICATED)); EffectiveAcl effectiveAcl = new EffectiveAcl(acl, Optional.of(creator), Optional.of(owner)); assertTrue(effectiveAcl.hasPermission(creator, Permission.CREATE)); assertTrue(effectiveAcl.hasPermission(creator, Permission.VIEW)); assertFalse(effectiveAcl.hasPermission(creator, Permission.UPDATE)); assertTrue(effectiveAcl.hasPermission(owner, Permission.VIEW)); assertTrue(effectiveAcl.hasPermission(owner, Permission.UPDATE)); assertTrue(effectiveAcl.hasPermission(other, Permission.CREATE)); assertFalse(effectiveAcl.hasPermission(other, Permission.VIEW)); assertFalse(effectiveAcl.hasPermission(other, Permission.UPDATE)); } private User createUser(Collection<? extends Role> roles) { User user = new User("email", "password"); user.setId(id++); for(Role role : roles) { user.getRoles().add(new UserRole(user, role)); } return user; } }
arrayexpress/annotare2
app/om/src/test/java/uk/ac/ebi/fg/annotare2/db/model/EffectiveAclTest.java
Java
apache-2.0
2,655
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.nextreports.server.web.common.util; /** * Display a message in firebug's console. * * @author Decebal Suiu */ public class FirebugLogger { public static String log(String message) { StringBuilder builder = new StringBuilder(); builder.append("var console = window['console'];"); builder.append("if (console && console.log) {"); builder.append("console.log('" + message + "');"); builder.append("}"); return builder.toString(); } }
nextreports/nextreports-server
src/ro/nextreports/server/web/common/util/FirebugLogger.java
Java
apache-2.0
1,276
package com.mqvisualizer.core.message.body; import com.mqvisualizer.model.message.JmsObjectMessage; import javafx.beans.value.ObservableValue; import java.io.Serializable; /** * Created by Mykolas on 2014-09-11. */ public class JmsObjectMessageBodyViewModel extends JmsMessageBodyViewModel<Serializable> { private JmsObjectMessage jmsObjectMessage; public JmsObjectMessageBodyViewModel(JmsObjectMessage jmsObjectMessage) { super(jmsObjectMessage.getObjectSilent()); this.jmsObjectMessage = jmsObjectMessage; } @Override public Serializable getInitContent() { return jmsObjectMessage.getObjectSilent(); } @Override public void changed(ObservableValue<? extends Serializable> observable, Serializable oldValue, Serializable newValue) { jmsObjectMessage.setObjectSilent(newValue); } }
SilentScope/mq-visualizer
src/mq-visualizer-core/src/main/java/com/mqvisualizer/core/message/body/JmsObjectMessageBodyViewModel.java
Java
apache-2.0
859
package org.gradle.test.performance.mediummonolithicjavaproject.p219; import org.junit.Test; import static org.junit.Assert.*; public class Test4388 { Production4388 objectUnderTest = new Production4388(); @Test public void testProperty0() { String value = "value"; objectUnderTest.setProperty0(value); assertEquals(value, objectUnderTest.getProperty0()); } @Test public void testProperty1() { String value = "value"; objectUnderTest.setProperty1(value); assertEquals(value, objectUnderTest.getProperty1()); } @Test public void testProperty2() { String value = "value"; objectUnderTest.setProperty2(value); assertEquals(value, objectUnderTest.getProperty2()); } @Test public void testProperty3() { String value = "value"; objectUnderTest.setProperty3(value); assertEquals(value, objectUnderTest.getProperty3()); } @Test public void testProperty4() { String value = "value"; objectUnderTest.setProperty4(value); assertEquals(value, objectUnderTest.getProperty4()); } @Test public void testProperty5() { String value = "value"; objectUnderTest.setProperty5(value); assertEquals(value, objectUnderTest.getProperty5()); } @Test public void testProperty6() { String value = "value"; objectUnderTest.setProperty6(value); assertEquals(value, objectUnderTest.getProperty6()); } @Test public void testProperty7() { String value = "value"; objectUnderTest.setProperty7(value); assertEquals(value, objectUnderTest.getProperty7()); } @Test public void testProperty8() { String value = "value"; objectUnderTest.setProperty8(value); assertEquals(value, objectUnderTest.getProperty8()); } @Test public void testProperty9() { String value = "value"; objectUnderTest.setProperty9(value); assertEquals(value, objectUnderTest.getProperty9()); } }
oehme/analysing-gradle-performance
my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p219/Test4388.java
Java
apache-2.0
2,111
require 'spec_helper' require 'rack/test' module Bosh::Director module Api describe Controllers::LinkProvidersController do include Rack::Test::Methods subject(:app) { described_class.new(config) } let(:config) do config = Config.load_hash(SpecHelper.spec_get_director_config) identity_provider = Support::TestIdentityProvider.new(config.get_uuid_provider) allow(config).to receive(:identity_provider).and_return(identity_provider) config end before do App.new(config) basic_authorize 'admin', 'admin' end context 'when checking link provider' do let(:deployment) { Models::Deployment.create(:name => 'test_deployment', :manifest => YAML.dump({'foo' => 'bar'})) } it 'list providers endpoint exists' do get "/?deployment=#{deployment.name}" expect(last_response.status).to eq(200) end context 'when teams are used' do let(:dev_team) { Models::Team.create(:name => 'dev') } let(:other_team) { Models::Team.create(:name => 'other') } let!(:owned_deployment) { Models::Deployment.create_with_teams(:name => 'owned_deployment', teams: [dev_team], manifest: YAML.dump({'foo' => 'bar'})) } let!(:other_deployment) { Models::Deployment.create_with_teams(:name => 'other_deployment', teams: [other_team], manifest: YAML.dump({'foo' => 'bar'})) } before do basic_authorize 'dev-team-member', 'dev-team-member' end it 'allows access to owned deployment' do expect(get("/?deployment=#{owned_deployment.name}").status).to eq(200) end it 'denies access to other deployment' do expect(get("/?deployment=#{other_deployment.name}").status).to eq(401) end end context 'when user has read access' do before do basic_authorize 'reader', 'reader' end it 'returns the links' do get "/?deployment=#{deployment.name}" expect(last_response.status).to eq(200) end end it 'with invalid link deployment name' do get '/?deployment=invalid_deployment_name' expect(last_response.status).to eq(404) expect(last_response.body).to eq("{\"code\":70000,\"description\":\"Deployment 'invalid_deployment_name' doesn't exist\"}") end it 'returns 400 if deployment name is not provided' do get '/' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"code":190024,"description":"Deployment name is required"}') end context 'and there are providers in the database' do let!(:provider_1) do Models::Links::LinkProvider.create( :deployment => deployment, :instance_group => 'instance_group', :type => 'job', :name => 'job_name_1', ) end let!(:provider_intent_1a) do Models::Links::LinkProviderIntent.create( :name => 'link_name_1a', :link_provider => provider_1, :shared => true, :consumable => true, :type => 'link_type_1a', :original_name => 'link_original_name_1a', :content => 'some link content', ) end let!(:provider_intent_1b) do Models::Links::LinkProviderIntent.create( :name => 'link_name_1b', :link_provider => provider_1, :shared => true, :consumable => true, :type => 'link_type_1b', :original_name => 'link_original_name_1b', :content => 'some link content', ) end let!(:provider_2) do Models::Links::LinkProvider.create( :deployment => deployment, :instance_group => 'instance_group', :type => 'job', :name => 'job_name_2', ) end let!(:provider_intent_2) do Models::Links::LinkProviderIntent.create( :name => 'link_name_2', :link_provider => provider_2, :shared => false, :consumable => true, :type => 'link_type_2', :original_name => 'link_original_name_2', :content => 'I have content', ) end it 'should return a list of providers for specified deployment' do get "/?deployment=#{provider_1.deployment.name}" expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq([generate_provider_hash(provider_intent_1a),generate_provider_hash(provider_intent_1b),generate_provider_hash(provider_intent_2)]) end end end def generate_provider_hash(model) provider = model.link_provider { 'id' => model.id.to_s, 'name' => model.name, 'shared' => model.shared, 'deployment' => provider.deployment.name, 'link_provider_definition' => { 'type' => model.type, 'name' => model.original_name, }, 'owner_object' => { 'type' => provider.type, 'name' => provider.name, 'info' => { 'instance_group' => provider.instance_group, } } } end end end end
barthy1/bosh
src/bosh-director/spec/unit/api/controllers/link_providers_controller_spec.rb
Ruby
apache-2.0
5,581
package com.fasterxml.jackson.dataformat.yaml; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.format.DataFormatDetector; import com.fasterxml.jackson.core.format.DataFormatMatcher; import com.fasterxml.jackson.core.format.MatchStrength; public class FormatDetectionTest extends ModuleTestBase { /** * One nifty thing YAML has is the "---" start-doc indicator, which * makes it possible to auto-detect format... */ public void testFormatDetection() throws Exception { YAMLFactory yamlF = new YAMLFactory(); JsonFactory jsonF = new JsonFactory(); DataFormatDetector det = new DataFormatDetector(new JsonFactory[] { yamlF, jsonF }); // let's accept about any match; but only if no "solid match" found det = det.withMinimalMatch(MatchStrength.WEAK_MATCH).withOptimalMatch(MatchStrength.SOLID_MATCH); // First, give a JSON document... DataFormatMatcher match = det.findFormat("{ \"name\" : \"Bob\" }".getBytes("UTF-8")); assertNotNull(match); assertEquals(jsonF.getFormatName(), match.getMatchedFormatName()); // and verify we can parse it JsonParser p = match.createParserWithMatch(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("name", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Bob", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); // then YAML match = det.findFormat("---\nname: Bob\n".getBytes("UTF-8")); assertNotNull(match); assertEquals(yamlF.getFormatName(), match.getMatchedFormatName()); // and parsing p = match.createParserWithMatch(); assertToken(JsonToken.START_OBJECT, p.nextToken()); assertToken(JsonToken.FIELD_NAME, p.nextToken()); assertEquals("name", p.getCurrentName()); assertToken(JsonToken.VALUE_STRING, p.nextToken()); assertEquals("Bob", p.getText()); assertToken(JsonToken.END_OBJECT, p.nextToken()); p.close(); } }
jprante/elasticsearch-client
jackson-dataformat-yaml/src/test/java/com/fasterxml/jackson/dataformat/yaml/FormatDetectionTest.java
Java
apache-2.0
2,251
#include "gtest/gtest.h" #include <pistache/net.h> #include <iostream> #include <stdexcept> #include <arpa/inet.h> #include <netinet/in.h> #include <sys/socket.h> using namespace Pistache; TEST(net_test, port_creation) { Port port1(3000); ASSERT_FALSE(port1.isReserved()); uint16_t value1 = port1; ASSERT_EQ(value1, 3000); ASSERT_EQ(port1.toString(), "3000"); Port port2(80); ASSERT_TRUE(port2.isReserved()); uint16_t value2 = port2; ASSERT_EQ(value2, 80); ASSERT_EQ(port2.toString(), "80"); } TEST(net_test, address_creation) { Address address1("127.0.0.1:8080"); ASSERT_EQ(address1.host(), "127.0.0.1"); ASSERT_EQ(address1.family(), AF_INET); ASSERT_EQ(address1.port(), 8080); std::string addr = "127.0.0.1"; Address address2(addr, Port(8080)); ASSERT_EQ(address2.host(), "127.0.0.1"); ASSERT_EQ(address2.family(), AF_INET); ASSERT_EQ(address2.port(), 8080); Address address3(Ipv4(127, 0, 0, 1), Port(8080)); ASSERT_EQ(address3.host(), "127.0.0.1"); ASSERT_EQ(address3.family(), AF_INET); ASSERT_EQ(address3.port(), 8080); Address address4(Ipv4::any(), Port(8080)); ASSERT_EQ(address4.host(), "0.0.0.0"); ASSERT_EQ(address4.family(), AF_INET); ASSERT_EQ(address4.port(), 8080); Address address5("*:8080"); ASSERT_EQ(address5.host(), "0.0.0.0"); ASSERT_EQ(address5.family(), AF_INET); ASSERT_EQ(address5.port(), 8080); Address address6("[::1]:8080"); ASSERT_EQ(address6.host(), "::1"); ASSERT_EQ(address6.family(), AF_INET6); ASSERT_EQ(address6.port(), 8080); std::string addr2 = "[::1]"; Address address7(addr2, Port(8080)); ASSERT_EQ(address7.host(), "::1"); ASSERT_EQ(address7.family(), AF_INET6); ASSERT_EQ(address7.port(), 8080); Address address8(Ipv6(0, 0, 0, 0, 0, 0, 0, 1), Port(8080)); ASSERT_EQ(address8.host(), "::1"); ASSERT_EQ(address8.family(), AF_INET6); ASSERT_EQ(address8.port(), 8080); Address address9(Ipv6::any(true), Port(8080)); ASSERT_EQ(address9.host(), "::"); ASSERT_EQ(address9.family(), AF_INET6); ASSERT_EQ(address9.port(), 8080); Address address10("[::]:8080"); ASSERT_EQ(address10.host(), "::"); ASSERT_EQ(address10.family(), AF_INET6); ASSERT_EQ(address10.port(), 8080); Address address11("[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]:8080"); ASSERT_EQ(address11.host(), "2001:db8:aabb:ccdd:eeff:11:2233:4455"); ASSERT_EQ(address11.family(), AF_INET6); ASSERT_EQ(address11.port(), 8080); Address address12(Ipv4::loopback(), Port(8080)); ASSERT_EQ(address12.host(), "127.0.0.1"); ASSERT_EQ(address12.family(), AF_INET); ASSERT_EQ(address12.port(), 8080); Address address13(Ipv6::loopback(true), Port(8080)); ASSERT_EQ(address13.host(), "::1"); ASSERT_EQ(address13.family(), AF_INET6); ASSERT_EQ(address13.port(), 8080); Address address14("127.0.0.1"); ASSERT_EQ(address14.host(), "127.0.0.1"); ASSERT_EQ(address14.family(), AF_INET); ASSERT_EQ(address14.port(), 80); Address address15("www.example.com"); ASSERT_EQ(address15.host(), "93.184.216.34"); ASSERT_EQ(address15.family(), AF_INET); ASSERT_EQ(address15.port(), 80); Address address16(IP(127, 0, 0, 1), Port(8080)); ASSERT_EQ(address16.host(), "127.0.0.1"); ASSERT_EQ(address16.family(), AF_INET); ASSERT_EQ(address16.port(), 8080); Address address17(IP::any(), Port(8080)); ASSERT_EQ(address17.host(), "0.0.0.0"); ASSERT_EQ(address17.family(), AF_INET); ASSERT_EQ(address17.port(), 8080); Address address18(IP(2, 0, 0, 0, 0, 0, 0, 1), Port(8080)); ASSERT_EQ(address18.host(), "2::1"); ASSERT_EQ(address18.family(), AF_INET6); ASSERT_EQ(address18.port(), 8080); Address address19(IP::any(true), Port(8080)); ASSERT_EQ(address19.host(), "::"); ASSERT_EQ(address19.family(), AF_INET6); ASSERT_EQ(address19.port(), 8080); Address address20(IP::loopback(true), Port(8080)); ASSERT_EQ(address20.host(), "::1"); ASSERT_EQ(address20.family(), AF_INET6); ASSERT_EQ(address20.port(), 8080); Address address21(IP::loopback(), Port(8080)); ASSERT_EQ(address21.host(), "127.0.0.1"); ASSERT_EQ(address21.family(), AF_INET); ASSERT_EQ(address21.port(), 8080); Address address22("[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]"); ASSERT_EQ(address22.host(), "2001:db8:aabb:ccdd:eeff:11:2233:4455"); ASSERT_EQ(address22.family(), AF_INET6); ASSERT_EQ(address22.port(), 80); Address address23("[::]"); ASSERT_EQ(address23.host(), "::"); ASSERT_EQ(address23.family(), AF_INET6); ASSERT_EQ(address23.port(), 80); } TEST(net_test, invalid_address) { ASSERT_THROW(Address("127.0.0.1:9999999"), std::invalid_argument); ASSERT_THROW(Address("127.0.0.1:"), std::invalid_argument); ASSERT_THROW(Address("127.0.0.1:-10"), std::invalid_argument); ASSERT_THROW(Address("[GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG:GGGG]:8080"); , std::invalid_argument); ASSERT_THROW(Address("[::GGGG]:8080");, std::invalid_argument); ASSERT_THROW(Address("256.256.256.256:8080");, std::invalid_argument); ASSERT_THROW(Address("1.0.0.256:8080");, std::invalid_argument); } TEST(net_test, address_parser) { AddressParser ap1("127.0.0.1:80"); ASSERT_EQ(ap1.rawHost(), "127.0.0.1"); ASSERT_EQ(ap1.rawPort(), "80"); ASSERT_EQ(ap1.family(), AF_INET); ASSERT_EQ(ap1.hasColon(), true); AddressParser ap2("example.com"); ASSERT_EQ(ap2.rawHost(), "example.com"); ASSERT_EQ(ap2.rawPort(), ""); ASSERT_EQ(ap2.family(), AF_INET); ASSERT_EQ(ap2.hasColon(), false); AddressParser ap3("[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]:8080"); ASSERT_EQ(ap3.rawHost(), "[2001:0DB8:AABB:CCDD:EEFF:0011:2233:4455]"); ASSERT_EQ(ap3.rawPort(), "8080"); ASSERT_EQ(ap3.family(), AF_INET6); ASSERT_THROW(AddressParser("127.0.0.1:");, std::invalid_argument); ASSERT_THROW(AddressParser("[::]:");, std::invalid_argument); }
oktal/pistache
tests/net_test.cc
C++
apache-2.0
5,823
package com.github.ccook.gtk.library; import com.github.ccook.gtk.model.GdkEvent; import com.github.ccook.gtk.model.GtkTextDirection; import com.github.ccook.gtk.model.PangoLanguage; import com.github.ccook.gtk.model.object.GtkWidget; import com.sun.jna.Callback; import com.sun.jna.Library; import com.sun.jna.Native; /** * Created by cam on 10/22/16. */ public interface GtkLibrary extends Library { GtkLibrary INSTANCE = (GtkLibrary) Native.loadLibrary("libgtk-3", GtkLibrary.class); interface sig_t extends Callback { void invoke(); } /** * Prevents gtk_init(), gtk_init_check(), gtk_init_with_args() and gtk_parse_args() from automatically calling * setlocale (LC_ALL, ""). * You would want to use this function if you wanted to set the locale for your program to something other than the * user’s locale, or if you wanted to set different values for different locale categories. * Most programs should not need to call this function. */ void gtk_disable_setlocale(); /** * Returns the PangoLanguage for the default language currently in effect. (Note that this can change over the life * of an application.) The default language is derived from the current locale. It determines, for example, whether * GTK+ uses the right-to-left or left-to-right text direction. * This function is equivalent to pango_language_get_default(). See that function for details. * * @return the default language as a PangoLanguage, must not be freed. */ PangoLanguage gtk_get_default_language(); /** * Get the direction of the current locale. This is the expected reading direction for text and UI. * This function depends on the current locale being set with setlocale() and will default to setting the * GTK_TEXT_DIR_LTR direction otherwise. GTK_TEXT_DIR_NONE will never be returned. * GTK+ sets the default text direction according to the locale during gtk_init(), and you should normally * use gtk_widget_get_direction() or gtk_widget_get_default_direction() to obtain the current direcion. * This function is only needed rare cases when the locale is changed after GTK+ has already been initialized. * In this case, you can use it to update the default text direction as follows: * * @return the GtkTextDirection of the current locale */ GtkTextDirection gtk_get_locale_direction(); /** * Parses command line arguments, and initializes global attributes of GTK+, but does not actually open a connection * to a display. (See gdk_display_open(), gdk_get_display_arg_name()) * Any arguments used by GTK+ or GDK are removed from the array and argc and argv are updated accordingly. * There is no need to call this function explicitly if you are using gtk_init(), or gtk_init_check(). * Note that many aspects of GTK+ require a display connection to function, so this way of initializing GTK+ is * really only useful for specialized use cases. * * @param argc a pointer to the number of command line arguments. * @param argv a pointer to the array of command line arguments. * @return TRUE if initialization succeeded, otherwise FALSE */ boolean gtk_parse_args(int argc, String[] argv); /** * Call this function before using any other GTK+ functions in your GUI applications. It will initialize everything * needed to operate the toolkit and parses some standard command line options. * Although you are expected to pass the argc , argv parameters from main() to this function, it is possible to pass * NULL if argv is not available or commandline handling is not required. * argc and argv are adjusted accordingly so your own code will never see those standard arguments. * Note that there are some alternative ways to initialize GTK+: if you are calling gtk_parse_args(), * gtk_init_check(), gtk_init_with_args() or g_option_context_parse() with the option group returned by * gtk_get_option_group(), you don’t have to call gtk_init(). * And if you are using GtkApplication, you don't have to call any of the initialization functions either; * the “startup” handler does it for you. * This function will terminate your program if it was unable to initialize the windowing system for some reason. * If you want your program to fall back to a textual interface you want to call gtk_init_check() instead. * Since 2.18, GTK+ calls signal (SIGPIPE, SIG_IGN) during initialization, to ignore SIGPIPE signals, * since these are almost never wanted in graphical applications. If you do need to handle SIGPIPE for some reason, * reset the handler after gtk_init(), but notice that other libraries (e.g. libdbus or gvfs) might * do similar things. */ void gtk_init(int argc, String[] argv); /** * This function does the same work as gtk_init() with only a single change: It does not terminate the program * if the windowing system can’t be initialized. Instead it returns FALSE on failure. * This way the application can fall back to some other means of communication with the user - * for example a curses or command line interface. * * @param argc Address of the argc parameter of your main() function (or 0 if argv is NULL). * This will be changed if any arguments were handled. * @param argv Address of the argv parameter of main(), or NULL. Any options understood by * GTK+ are stripped before return. * @return TRUE if the windowing system has been successfully initialized, FALSE otherwise */ boolean gtk_init_check(int argc, String[] argv); /** * This function does the same work as gtk_init_check(). * Additionally, it allows you to add your own commandline options, and it automatically generates nicely formatted * --help output. Note that your program will be terminated after writing out the help output. * * @param argc Address of the argc parameter of your main() function (or 0 if argv is NULL). * This will be changed if any arguments were handled. * @param argv Address of the argv parameter of main(), or NULL. Any options understood by GTK+ are * stripped before return. * @param parameter_string a string which is displayed in the first line of --help output, * after programname [OPTION...]. * @param entries a NULL-terminated array of GOptionEntrys describing the options of your program. * @param translation_domain a translation domain to use for translating the --help output for the options in * entries and the parameter_string with gettext(), or NULL. * @param error a return location for errors * @return TRUE if the windowing system has been successfully initialized, FALSE otherwise */ //boolean gtk_init_with_args(int argc, String[] argv, String parameter_string, GOptionEntry[] entries, String translation_domain, GError error); /** * Returns a GOptionGroup for the commandline arguments recognized by GTK+ and GDK. * You should add this group to your GOptionContext with g_option_context_add_group(), * if you are using g_option_context_parse() to parse your commandline arguments. * * @param open_default_display whether to open the default display when parsing the commandline arguments * @return a GOptionGroup for the commandline arguments recognized by GTK+. */ //GOptionGroup gtk_get_option_group(boolean open_default_display); /** * Checks if any events are pending. * This can be used to update the UI and invoke timeouts etc. while doing some time intensive computation. * * @return TRUE if any events are pending, FALSE otherwise */ boolean gtk_events_pending(); /** * Runs the main loop until gtk_main_quit() is called. * You can nest calls to gtk_main(). * In that case gtk_main_quit() will make the innermost invocation of the main loop return. */ void gtk_main(); /** * Asks for the current nesting level of the main loop. * * @return the nesting level of the current invocation of the main loop */ int gtk_main_level(); /** * Makes the innermost invocation of the main loop return when it regains control. */ void gtk_main_quit(); /** * Runs a single iteration of the mainloop. * If no events are waiting to be processed GTK+ will block until the next event is noticed. * If you don’t want to block look at gtk_main_iteration_do() or check if any events are pending * with gtk_events_pending() first. * * @return TRUE if gtk_main_quit() has been called for the innermost mainloop */ boolean gtk_main_iteration(); /** * Runs a single iteration of the mainloop. * If no events are available either return or block depending on the value of blocking . * * @param blocking TRUE if you want GTK+ to block if no events are pending * @return TRUE if gtk_main_quit() has been called for the innermost mainloop */ boolean gtk_main_iteration_do(boolean blocking); /** * Processes a single GDK event. * This is public only to allow filtering of events between GDK and GTK+. You will not usually need to call this * function directly. * While you should not call this function directly, you might want to know how exactly events are handled. * So here is what this function does with the event: * Compress enter/leave notify events. If the event passed build an enter/leave pair together with the next event * (peeked from GDK), both events are thrown away. This is to avoid a backlog of (de-)highlighting widgets * crossed by the pointer. * Find the widget which got the event. If the widget can’t be determined the event is thrown away unless it * belongs to a INCR transaction. * Then the event is pushed onto a stack so you can query the currently handled event with gtk_get_current_event(). * The event is sent to a widget. If a grab is active all events for widgets that are not in the contained in the * grab widget are sent to the latter with a few exceptions: * Deletion and destruction events are still sent to the event widget for obvious reasons. * Events which directly relate to the visual representation of the event widget. * Leave events are delivered to the event widget if there was an enter event delivered to it before without the * paired leave event. * Drag events are not redirected because it is unclear what the semantics of that would be. Another point of * interest might be that all key events are first passed through the key snooper functions if there are any. * Read the description of gtk_key_snooper_install() if you need this feature. * After finishing the delivery the event is popped from the event stack. * * @param event An event to process (normally passed by GDK) */ void gtk_main_do_event(GdkEvent event); /** * All this function does it to return TRUE. * This can be useful for example if you want to inhibit the deletion of a window. * Of course you should not do this as the user expects a reaction from clicking the close icon of the window... * * @return TRUE */ boolean gtk_true(); /** * Analogical to gtk_true(), this function does nothing but always returns FALSE. * * @return FALSE */ boolean gtk_false(); /** * Makes widget the current grabbed widget. * This means that interaction with other widgets in the same application is blocked * and mouse as well as keyboard events are delivered to this widget. * If widget is not sensitive, it is not set as the current grabbed widget and this function does nothing. * * @param widget */ void gtk_grab_add(GtkWidget widget); }
Ccook/gtk-java-bindings
src/main/java/com/github/ccook/gtk/library/GtkLibrary.java
Java
apache-2.0
12,211
/* * Copyright (c) 2015 Andrew Coates * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.datalorax.populace.core.walk.inspector.annotation; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.lang.reflect.Field; import java.lang.reflect.Method; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ChainedAnnotationInspectorTest { private final Field field; private final Test annotation1; private final Test annotation2; private final Method[] methods; private AnnotationInspector first; private AnnotationInspector second; private ChainedAnnotationInspector inspector; public ChainedAnnotationInspectorTest() throws Exception { this.field = getClass().getDeclaredField("field"); this.annotation1 = getClass().getDeclaredMethod("dummyTest").getAnnotation(Test.class); this.annotation2 = getClass().getDeclaredMethod("shouldTestEqualsAndHashCode").getAnnotation(Test.class); this.methods = new Method[1]; } @BeforeMethod public void setUp() throws Exception { first = mock(AnnotationInspector.class); second = mock(AnnotationInspector.class); inspector = new ChainedAnnotationInspector(first, second); } @Test public void shouldGetFieldAnnotationFromFirstInspectorIfPresent() throws Exception { // Given: when(first.getAnnotation(field, Test.class)).thenReturn(annotation1); when(second.getAnnotation(field, Test.class)).thenReturn(annotation2); // When: final Test annotation = inspector.getAnnotation(field, Test.class); // Then: assertThat(annotation, is(annotation1)); } @Test public void shouldGetFieldAnnotationFromSecondInspectorIfFirstReturnsNull() throws Exception { // Given: when(first.getAnnotation(field, Test.class)).thenReturn(null); when(second.getAnnotation(field, Test.class)).thenReturn(annotation2); // When: final Test annotation = inspector.getAnnotation(field, Test.class); // Then: assertThat(annotation, is(annotation2)); } @Test public void shouldGetMethodAnnotationFromFirstInspectorIfPresent() throws Exception { // Given: when(first.getAnnotation(Test.class, methods)).thenReturn(annotation1); when(second.getAnnotation(Test.class, methods)).thenReturn(annotation2); // When: final Test annotation = inspector.getAnnotation(Test.class, methods); // Then: assertThat(annotation, is(annotation1)); } @Test public void shouldGetMethodAnnotationFromSecondInspectorIfFirstReturnsNull() throws Exception { // Given: when(first.getAnnotation(Test.class, methods)).thenReturn(null); when(second.getAnnotation(Test.class, methods)).thenReturn(annotation2); // When: final Test annotation = inspector.getAnnotation(Test.class, methods); // Then: assertThat(annotation, is(annotation2)); } @Test public void shouldTestEqualsAndHashCode() throws Exception { new EqualsTester() .addEqualityGroup( new ChainedAnnotationInspector(first, second), new ChainedAnnotationInspector(first, second)) .addEqualityGroup( new ChainedAnnotationInspector(second, first)) .addEqualityGroup( new ChainedAnnotationInspector(mock(AnnotationInspector.class, "2"), second)) .addEqualityGroup( new ChainedAnnotationInspector(first, mock(AnnotationInspector.class, "2"))) .testEquals(); } @Test public void shouldThrowNPEsOnConstructorParams() throws Exception { new NullPointerTester() .setDefault(AnnotationInspector.class, mock(AnnotationInspector.class)) .testAllPublicConstructors(ChainedAnnotationInspector.class); } @Test(enabled = false) public void dummyTest() { } }
datalorax/populace
populace-core/src/test/java/org/datalorax/populace/core/walk/inspector/annotation/ChainedAnnotationInspectorTest.java
Java
apache-2.0
4,782
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.spargel.java.record; import java.util.Iterator; import org.apache.flink.types.Record; import org.apache.flink.types.Value; public final class MessageIterator<Message extends Value> implements Iterator<Message>, Iterable<Message> { private final Message instance; private Iterator<Record> source; public MessageIterator(Message instance) { this.instance = instance; } public final void setSource(Iterator<Record> source) { this.source = source; } @Override public final boolean hasNext() { return this.source.hasNext(); } @Override public final Message next() { this.source.next().getFieldInto(1, this.instance); return this.instance; } @Override public final void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<Message> iterator() { return this; } }
citlab/vs.msc.ws14
flink-0-7-custom/flink-addons/flink-spargel/src/main/java/org/apache/flink/spargel/java/record/MessageIterator.java
Java
apache-2.0
1,663
using Reyx.Web.Workshop.Knockout.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Reyx.Web.Workshop.Knockout { public class Settings { private const string SETTINGS_USER = "Settings.User"; public static User User { get { return (User)System.Web.HttpContext.Current.Session[SETTINGS_USER]; } set { System.Web.HttpContext.Current.Session[SETTINGS_USER] = value; } } } }
reyx/Reyx.Web.Workshop.Knockout
Reyx.Web.Workshop.Knockout/Settings.cs
C#
apache-2.0
605
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Replace Network Acl Association Request Marshaller */ public class ReplaceNetworkAclAssociationRequestMarshaller implements Marshaller<Request<ReplaceNetworkAclAssociationRequest>, ReplaceNetworkAclAssociationRequest> { public Request<ReplaceNetworkAclAssociationRequest> marshall(ReplaceNetworkAclAssociationRequest replaceNetworkAclAssociationRequest) { if (replaceNetworkAclAssociationRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<ReplaceNetworkAclAssociationRequest> request = new DefaultRequest<ReplaceNetworkAclAssociationRequest>(replaceNetworkAclAssociationRequest, "AmazonEC2"); request.addParameter("Action", "ReplaceNetworkAclAssociation"); request.addParameter("Version", "2012-08-15"); if (replaceNetworkAclAssociationRequest.getAssociationId() != null) { request.addParameter("AssociationId", StringUtils.fromString(replaceNetworkAclAssociationRequest.getAssociationId())); } if (replaceNetworkAclAssociationRequest.getNetworkAclId() != null) { request.addParameter("NetworkAclId", StringUtils.fromString(replaceNetworkAclAssociationRequest.getNetworkAclId())); } return request; } }
frsyuki/aws-sdk-for-java
src/main/java/com/amazonaws/services/ec2/model/transform/ReplaceNetworkAclAssociationRequestMarshaller.java
Java
apache-2.0
2,234
package pl.devoxx.dojrzewatr; import com.ofg.infrastructure.environment.EnvironmentSetupVerifier; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; import java.util.Arrays; import static com.ofg.config.BasicProfiles.*; @SpringBootApplication @EnableAsync public class Application { public static void main(String[] args) { SpringApplication application = new SpringApplication(Application.class); application.addListeners(new EnvironmentSetupVerifier(Arrays.asList(DEVELOPMENT, PRODUCTION, TEST))); application.run(args); } }
2015-06-devoxx-microservices/dojrzewatr.io
src/main/java/pl/devoxx/dojrzewatr/Application.java
Java
apache-2.0
695
/** * Module that controls the Dataverse node settings. Includes Knockout view-model * for syncing data. */ var ko = require('knockout'); var bootbox = require('bootbox'); require('knockout.punches'); var Raven = require('raven-js'); var osfHelpers = require('js/osfHelpers'); ko.punches.enableAll(); function ViewModel(url) { var self = this; self.url = url; self.urls = ko.observable(); self.dataverseUsername = ko.observable(); self.dataversePassword = ko.observable(); self.ownerName = ko.observable(); self.nodeHasAuth = ko.observable(false); self.userHasAuth = ko.observable(false); self.userIsOwner = ko.observable(false); self.connected = ko.observable(false); self.loadedSettings = ko.observable(false); self.loadedStudies = ko.observable(false); self.submitting = ko.observable(false); self.dataverses = ko.observableArray([]); self.studies = ko.observableArray([]); self.badStudies = ko.observableArray([]); self.savedStudyHdl = ko.observable(); self.savedStudyTitle = ko.observable(); self.savedDataverseAlias = ko.observable(); self.savedDataverseTitle = ko.observable(); self.studyWasFound = ko.observable(false); self.messages = { userSettingsError: ko.pureComputed(function() { return 'Could not retrieve settings. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }), confirmNodeDeauth: ko.pureComputed(function() { return 'Are you sure you want to unlink this Dataverse account? This will ' + 'revoke the ability to view, download, modify, and upload files ' + 'to studies on the Dataverse from the OSF. This will not remove your ' + 'Dataverse authorization from your <a href="' + self.urls().settings + '">user settings</a> ' + 'page.'; }), confirmImportAuth: ko.pureComputed(function() { return 'Are you sure you want to authorize this project with your Dataverse credentials?'; }), deauthError: ko.pureComputed(function() { return 'Could not unlink Dataverse at this time. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }), deauthSuccess: ko.pureComputed(function() { return 'Successfully unlinked your Dataverse account.'; }), authInvalid: ko.pureComputed(function() { return 'Your Dataverse username or password is invalid.'; }), authError: ko.pureComputed(function() { return 'There was a problem connecting to the Dataverse. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }), importAuthSuccess: ko.pureComputed(function() { return 'Successfully linked your Dataverse account'; }), importAuthError: ko.pureComputed(function() { return 'There was a problem connecting to the Dataverse. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }), studyDeaccessioned: ko.pureComputed(function() { return 'This study has already been deaccessioned on the Dataverse ' + 'and cannot be connected to the OSF.'; }), forbiddenCharacters: ko.pureComputed(function() { return 'This study cannot be connected due to forbidden characters ' + 'in one or more of the study\'s file names. This issue has been forwarded to our ' + 'development team.'; }), setInfoSuccess: ko.pureComputed(function() { var filesUrl = window.contextVars.node.urls.web + 'files/'; return 'Successfully linked study \'' + self.savedStudyTitle() + '\'. Go to the <a href="' + filesUrl + '">Files page</a> to view your content.'; }), setStudyError: ko.pureComputed(function() { return 'Could not connect to this study. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }), getStudiesError: ko.pureComputed(function() { return 'Could not load studies. Please refresh the page or ' + 'contact <a href="mailto: support@osf.io">support@osf.io</a> if the ' + 'problem persists.'; }) }; self.savedStudyUrl = ko.pureComputed(function() { return (self.urls()) ? self.urls().studyPrefix + self.savedStudyHdl() : null; }); self.savedDataverseUrl = ko.pureComputed(function() { return (self.urls()) ? self.urls().dataversePrefix + self.savedDataverseAlias() : null; }); self.selectedDataverseAlias = ko.observable(); self.selectedStudyHdl = ko.observable(); self.selectedDataverseTitle = ko.pureComputed(function() { for (var i = 0; i < self.dataverses().length; i++) { var data = self.dataverses()[i]; if (data.alias === self.selectedDataverseAlias()) { return data.title; } } return null; }); self.selectedStudyTitle = ko.pureComputed(function() { for (var i = 0; i < self.studies().length; i++) { var data = self.studies()[i]; if (data.hdl === self.selectedStudyHdl()) { return data.title; } } return null; }); self.dataverseHasStudies = ko.pureComputed(function() { return self.studies().length > 0; }); self.showStudySelect = ko.pureComputed(function() { return self.loadedStudies() && self.dataverseHasStudies(); }); self.showNoStudies = ko.pureComputed(function() { return self.loadedStudies() && !self.dataverseHasStudies(); }); self.showLinkedStudy = ko.pureComputed(function() { return self.savedStudyHdl(); }); self.showLinkDataverse = ko.pureComputed(function() { return self.userHasAuth() && !self.nodeHasAuth() && self.loadedSettings(); }); self.credentialsChanged = ko.pureComputed(function() { return self.nodeHasAuth() && !self.connected(); }); self.showInputCredentials = ko.pureComputed(function() { return (self.credentialsChanged() && self.userIsOwner()) || (!self.userHasAuth() && !self.nodeHasAuth() && self.loadedSettings()); }); self.hasDataverses = ko.pureComputed(function() { return self.dataverses().length > 0; }); self.hasBadStudies = ko.pureComputed(function() { return self.badStudies().length > 0; }); self.showNotFound = ko.pureComputed(function() { return self.savedStudyHdl() && self.loadedStudies() && !self.studyWasFound(); }); self.showSubmitStudy = ko.pureComputed(function() { return self.nodeHasAuth() && self.connected() && self.userIsOwner(); }); self.enableSubmitStudy = ko.pureComputed(function() { return !self.submitting() && self.dataverseHasStudies() && self.savedStudyHdl() !== self.selectedStudyHdl(); }); // Flashed messages self.message = ko.observable(''); self.messageClass = ko.observable('text-info'); // Update above observables with data from the server $.ajax({ url: url, type: 'GET', dataType: 'json' }).done(function(response) { // Update view model self.updateFromData(response.result); self.loadedSettings(true); }).fail(function(xhr, textStatus, error) { self.changeMessage(self.messages.userSettingsError, 'text-warning'); Raven.captureMessage('Could not GET dataverse settings', { url: url, textStatus: textStatus, error: error }); }); } /** * Update the view model from data returned from the server. */ ViewModel.prototype.updateFromData = function(data) { var self = this; self.urls(data.urls); self.dataverseUsername(data.dataverseUsername); self.ownerName(data.ownerName); self.nodeHasAuth(data.nodeHasAuth); self.userHasAuth(data.userHasAuth); self.userIsOwner(data.userIsOwner); if (self.nodeHasAuth()) { self.dataverses(data.dataverses); self.savedDataverseAlias(data.savedDataverse.alias); self.savedDataverseTitle(data.savedDataverse.title); self.selectedDataverseAlias(data.savedDataverse.alias); self.savendStudyHdl(data.savedStudy.hdl); self.savedStudyTitle(data.savedStudy.title); self.connected(data.connected); if (self.userIsOwner()) { self.getStudies(); // Sets studies, selectedStudyHdl } } }; ViewModel.prototype.setInfo = function() { var self = this; self.submitting(true); return osfHelpers.postJSON( self.urls().set, ko.toJS({ dataverse: { alias: self.selectedDataverseAlias }, study: { hdl: self.selectedStudyHdl } }) ).done(function() { self.submitting(false); self.savedDataverseAlias(self.selectedDataverseAlias()); self.savedDataverseTitle(self.selectedDataverseTitle()); self.savedStudyHdl(self.selectedStudyHdl()); self.savedStudyTitle(self.selectedStudyTitle()); self.studyWasFound(true); self.changeMessage(self.messages.setInfoSuccess, 'text-success'); }).fail(function(xhr, textStatus, error) { self.submitting(false); var errorMessage = (xhr.status === 410) ? self.messages.studyDeaccessioned : (xhr.status = 406) ? self.messages.forbiddenCharacters : self.messages.setStudyError; self.changeMessage(errorMessage, 'text-danger'); Raven.captureMessage('Could not authenticate with Dataverse', { url: self.urls().set, textStatus: textStatus, error: error }); }); }; /** * Looks for study in list of studies when first loaded. * This prevents an additional request to the server, but requires additional logic. */ ViewModel.prototype.findStudy = function() { var self = this; for (var i in self.studies()) { if (self.studies()[i].hdl === self.savedStudyHdl()) { self.studyWasFound(true); return; } } }; ViewModel.prototype.getStudies = function() { var self = this; self.studies([]); self.badStudies([]); self.loadedStudies(false); return osfHelpers.postJSON( self.urls().getStudies, ko.toJS({ alias: self.selectedDataverseAlias }) ).done(function(response) { self.studies(response.studies); self.badStudies(response.badStudies); self.loadedStudies(true); self.selectedStudyHdl(self.savedStudyHdl()); self.findStudy(); }).fail(function() { self.changeMessage(self.messages.getStudiesError, 'text-danger'); }); }; ViewModel.prototype.authorizeNode = function() { var self = this; return osfHelpers.putJSON( self.urls().importAuth, {} ).done(function(response) { self.updateFromData(response.result); self.changeMessage(self.messages.importAuthSuccess, 'text-success', 3000); }).fail(function() { self.changeMessage(self.messages.importAuthError, 'text-danger'); }); }; /** Send POST request to authorize Dataverse */ ViewModel.prototype.sendAuth = function() { var self = this; return osfHelpers.postJSON( self.urls().create, ko.toJS({ dataverse_username: self.dataverseUsername, dataverse_password: self.dataversePassword }) ).done(function() { // User now has auth self.authorizeNode(); }).fail(function(xhr) { var errorMessage = (xhr.status === 401) ? self.messages.authInvalid : self.messages.authError; self.changeMessage(errorMessage, 'text-danger'); }); }; /** * Send PUT request to import access token from user profile. */ ViewModel.prototype.importAuth = function() { var self = this; bootbox.confirm({ title: 'Link to Dataverse Account?', message: self.messages.confirmImportAuth(), callback: function(confirmed) { if (confirmed) { self.authorizeNode(); } } }); }; ViewModel.prototype.clickDeauth = function() { var self = this; function sendDeauth() { return $.ajax({ url: self.urls().deauthorize, type: 'DELETE' }).done(function() { self.nodeHasAuth(false); self.userIsOwner(false); self.connected(false); self.changeMessage(self.messages.deauthSuccess, 'text-success', 3000); }).fail(function() { self.changeMessage(self.messages.deauthError, 'text-danger'); }); } bootbox.confirm({ title: 'Deauthorize?', message: self.messages.confirmNodeDeauth(), callback: function(confirmed) { if (confirmed) { sendDeauth(); } } }); }; /** Change the flashed status message */ ViewModel.prototype.changeMessage = function(text, css, timeout) { var self = this; if (typeof text === 'function') { text = text(); } self.message(text); var cssClass = css || 'text-info'; self.messageClass(cssClass); if (timeout) { // Reset message after timeout period setTimeout(function() { self.message(''); self.messageClass('text-info'); }, timeout); } }; function DataverseNodeConfig(selector, url) { // Initialization code var self = this; self.selector = selector; self.url = url; // On success, instantiate and bind the ViewModel self.viewModel = new ViewModel(url); osfHelpers.applyBindings(self.viewModel, '#dataverseScope'); } module.exports = DataverseNodeConfig;
himanshuo/osf.io
website/addons/dataverse/static/dataverseNodeConfig.js
JavaScript
apache-2.0
14,334
/* * Copyright (c) 2005-2009 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.application.fees.util.helpers; import org.mifos.framework.exceptions.PropertyNotFoundException; public enum FeePayment { UPFRONT((short) 1), TIME_OF_DISBURSMENT((short) 2), TIME_OF_FIRSTLOANREPAYMENT((short) 3); private Short value; private FeePayment(Short value) { this.value = value; } public Short getValue() { return value; } public static FeePayment getFeePayment(Short value) throws PropertyNotFoundException { for (FeePayment feePayment : FeePayment.values()) { if (feePayment.getValue().equals(value)) { return feePayment; } } throw new PropertyNotFoundException("FeePayment"); } }
mifos/1.4.x
application/src/main/java/org/mifos/application/fees/util/helpers/FeePayment.java
Java
apache-2.0
1,490
package id.dreamfighter.android.utils; import org.apache.http.cookie.Cookie; import org.apache.http.impl.cookie.BasicClientCookie; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; /** * A wrapper class around {@link Cookie} and/or {@link BasicClientCookie} designed for use in {@link * PersistentCookieStore}. */ public class SerializableCookie implements Serializable { private static final long serialVersionUID = 6374381828722046732L; private transient final Cookie cookie; private transient BasicClientCookie clientCookie; public SerializableCookie(Cookie cookie) { this.cookie = cookie; } public Cookie getCookie() { Cookie bestCookie = cookie; if (clientCookie != null) { bestCookie = clientCookie; } return bestCookie; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(cookie.getName()); out.writeObject(cookie.getValue()); out.writeObject(cookie.getComment()); out.writeObject(cookie.getDomain()); out.writeObject(cookie.getExpiryDate()); out.writeObject(cookie.getPath()); out.writeInt(cookie.getVersion()); out.writeBoolean(cookie.isSecure()); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String name = (String) in.readObject(); String value = (String) in.readObject(); clientCookie = new BasicClientCookie(name, value); clientCookie.setComment((String) in.readObject()); clientCookie.setDomain((String) in.readObject()); clientCookie.setExpiryDate((Date) in.readObject()); clientCookie.setPath((String) in.readObject()); clientCookie.setVersion(in.readInt()); clientCookie.setSecure(in.readBoolean()); } }
dreamfighter/dreamlib
dreamlib/src/main/java/id/dreamfighter/android/utils/SerializableCookie.java
Java
apache-2.0
1,945
$LOAD_PATH << '..' require 'musikbot' MIN_ARTICLE_COUNT = 25 MAINTENANCE_CATEGORIES = [ 'All_articles_lacking_sources', 'All_articles_needing_additional_references', 'All_unreferenced_BLPs', 'All_BLP_articles_lacking_sources', 'All_articles_lacking_reliable_references', 'All_articles_with_a_promotional_tone', 'All_articles_with_topics_of_unclear_notability' ] REPORT_PAGE = 'Wikipedia:Database reports/Editors eligible for Autopatrol privilege' module AutopatrolledCandidates def self.run @mb = MusikBot::Session.new(inspect) users = {} page_creators.each_with_index do |user, i| username = user['user_name'] actor_id = user['actor_id'] # not sure how this happens next if username.nil? # Skip vanished users next if username.downcase.include?('vanished user') articles = articles_created(actor_id) # Make sure there are some articles created in the past month. Querying recent changes (30 days of data) # alone isn't enough because the page could have been moved from the mainspace. recent_article_count = articles.count { |a| @mb.parse_date(a['rev_timestamp']) > @mb.now - 365 } # Skip if they don't meet article count prerequisite or recently had a PERM request declined next if recent_article_count == 0 || articles.length < MIN_ARTICLE_COUNT || perm_request_declined?(username) user_data = { created: articles.length, edits: user['user_editcount'], deleted: deleted_counts(actor_id), blocks: block_count(username), tagged: maintenance_count(articles), perm_revoked: autopatrolled_revoked?(username), copyvios: scan_talk_page(username) } users[username] = user_data puts "#{i} of #{page_creators.length}: #{username} = #{articles.length}" end generate_report(users) end # Generate markup for the report and write it to REPORT_PAGE def self.generate_report(users) cat_str = MAINTENANCE_CATEGORIES.collect { |c| "[[:Category:#{c}|#{c.descore}]]" }.join(', ') markup = <<~END <div style='font-size:24px'>Users eligible to be autopatrolled as of #{I18n.l(@mb.today, format: :heading)}</div> {{FORMATNUM:#{users.length}}} users who have created an article in the past month, and may be eligible for the autopatrolled privilege but don't have it yet. Users who had a [[WP:PERM/A|request for autopatrolled]] declined in the past 90 days are not listed. Prepared by ~~~ <onlyinclude>~~~~~</onlyinclude> == Key == * '''Articles''': Number of live, non-redirect articles * '''Tagged''': Number of articles with maintenance tags<ref name=tags /> * '''Deleted''': Number of deleted articles in the past year (may include redirects)<ref name='deleted' /> * '''Edit count''': Raw edit count of the user * '''Blocks''': Number of blocks in the past year * '''Copyvios''': Number of ''possible'' user talk notifications about copyright concerns in the past year<ref name='copyvios' /> * '''Revoked?''': Whether or not the autopatrolled permission was previously revoked {{pb}} ;Notes {{reflist|refs=" <ref name='tags'>Supported maintenance categories include: #{cat_str}</ref> <ref name='deleted'>[[WP:G6|G6]] (technical) and [[WP:G7|G7]] (user-requested) speedy deletions are not included. The number of speedy, (BLP)PROD and AfD deletions are shown if detected via the deletion summary.</ref> <ref name='copyvios'>This works by scanning the edit summaries for "copyvios" or "copyright". Links are provided to the diffs, which may include removal of notices.</ref> }} == Report == {| class='wikitable sortable' ! Username ! Articles ! Tagged ! Deleted ! Edit count ! Blocks ! Copyvios ! Revoked? ! class="unsortable" | Links |- END # Sort by number of articles created users = users.sort_by { |username, data| -data[:created] }.to_h users.each do |username, data| user_rights_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&page=User:#{username.score}&type=rights" block_log = "https://en.wikipedia.org/w/index.php?title=Special:Log&action=view&page=#{username.score}&type=block" xtools_link = "[https://xtools.wmflabs.org/pages/?user=#{URI.escape(username)}" \ "&project=en.wikipedia.org&namespace=0&redirects=noredirects {{FORMATNUM:#{data[:created]}}}]" deleted_str = '0' # Generate string that lists the different types of deletions that were detected if data[:deleted][:total] > 0 deleted_str = "#{data[:deleted][:total]} total" deletion_stats = [] [:Speedy, :PROD, :AfD].each do |type| if data[:deleted][type] > 0 deletion_stats << "#{type}: {{FORMATNUM:#{data[:deleted][type]}}}" end end deleted_str += " (#{deletion_stats.join(', ')})".chomp('()') end block_str = data[:blocks] > 0 ? "[#{block_log} {{FORMATNUM:#{data[:blocks]}}}]" : '0' copyvios_str = 0 if data[:copyvios].any? copyvios_str = "#{data[:copyvios].length}<ref>" data[:copyvios].each do |rev_id| copyvios_str += "[https://en.wikipedia.org/wiki/Special:Diff/#{rev_id}]" end copyvios_str += "</ref>" end revoked_str = data[:perm_revoked] ? "[#{user_rights_log} Yes]" : 'No' links = [ "[[Special:UserRights/#{username}|User rights]]", "[https://xtools.wmflabs.org/ec/en.wikipedia.org?user=#{URI.encode(username)} EC]", "[https://xtools.wmflabs.org/categoryedits/en.wikipedia.org?username=#{URI.encode(username)}&categories=Living_people BLP edits]" ].join(' &middot; ') markup += <<~END | {{User0|#{username}}} | #{xtools_link} | {{FORMATNUM:#{data[:tagged]}}} | data-sort-value=#{data[:deleted][:total]} | #{deleted_str} | [[Special:Contributions/#{username}|{{FORMATNUM:#{data[:edits]}}}]] | #{block_str} | data-sort-value=#{data[:copyvios].length} | #{copyvios_str} | #{revoked_str} | #{links} |- END end markup = markup.chomp("\n|-") + <<~END |} ;Links {{reflist}} END @mb.edit(REPORT_PAGE, content: markup, summary: "Reporting #{users.length} users eligible for autopatrolled" ) end # Scan talk page history for messages that are potentially about copyvios def self.scan_talk_page(username) sql = %{ SELECT rev_id FROM revision_userindex LEFT OUTER JOIN comment ON rev_comment_id = comment_id WHERE rev_page = ( SELECT page_id FROM page WHERE page_title = ? AND page_namespace = 3 ) AND rev_timestamp > #{@mb.db_date(@mb.today - 365)} AND comment_text REGEXP "[Cc]opy(right|vio)" } @mb.repl_query(sql, username.score).to_a.collect { |r| r['rev_id'] } end # Get data about pages the user created that were deleted # Returns: # { # total: total number of articles deleted # Speedy: total number of articles deleted under [[WP:CSD]] # PROD: total number of articles deleted under [[WP:PROD]] or [[WP:BLPPROD]] # AfD: total number of articles deleted under [[WP:AfD]] # } def self.deleted_counts(actor_id) sql = %{ SELECT comment_text FROM logging_logindex LEFT OUTER JOIN comment ON log_comment_id = comment_id LEFT JOIN archive_userindex ON ar_page_id = log_page WHERE log_type = 'delete' AND ar_actor = ? AND ar_namespace = 0 AND ar_parent_id = 0 AND ar_timestamp > #{@mb.db_date(@mb.now - 365)} } counts = { total: 0, Speedy: 0, PROD: 0, AfD: 0 } @mb.repl_query(sql, actor_id).to_a.each do |data| # don't count technical or user-requested deletions next if data['comment_text'] =~ /\[\[WP:CSD#G(6|7)\|/ counts[:total] += 1 case data['comment_text'] when /\[\[WP:CSD#/ counts[:Speedy] += 1 when /\[\[WP:(BLP)?PROD/ counts[:PROD] += 1 when /\[\[(Wikipedia|WP):Articles for deletion\// counts[:AfD] += 1 end end counts end # Get the number of blocks the user had in the past year def self.block_count(username) sql = %{ SELECT COUNT(*) AS count FROM logging_logindex WHERE log_type = 'block' AND log_title = ? AND log_timestamp > #{@mb.db_date(@mb.now - 365)} } @mb.repl_query(sql, username.score).to_a.first['count'] end # Check if the user has had the autopatrolled permission revoked in the past def self.autopatrolled_revoked?(username) sql = %{ SELECT COUNT(*) AS count FROM logging_logindex WHERE log_type = 'rights' AND log_title = ? AND log_params REGEXP "oldgroups.*?autoreviewer.*?newgroups(?!.*?autoreviewer)" } @mb.repl_query(sql, username.score).to_a.first['count'] > 0 end # Get the page title, ID and creation date of articles created by the given user def self.articles_created(actor_id) sql = %{ SELECT page_title, page_id, rev_timestamp FROM revision_userindex LEFT JOIN page ON page_id = rev_page WHERE page_namespace = 0 AND rev_parent_id = 0 AND rev_actor = ? AND rev_deleted = 0 AND page_is_redirect = 0 } @mb.repl_query(sql, actor_id).to_a end # Get the number of articles created by the user that are in maintenance categories def self.maintenance_count(articles) # Create list of categories to be used in the `cl_to IN ()` clause categories_sql = MAINTENANCE_CATEGORIES.collect { |c| "'#{c}'" }.join(',') # Create list of article IDs to be used in the `cl_from IN ()` clause article_ids = articles .select { |a| @mb.parse_date(a['rev_timestamp']) > @mb.now - 365 } .collect { |a| a['page_id'] } sql = %{ SELECT COUNT(DISTINCT(cl_from)) AS count FROM categorylinks WHERE cl_from IN (#{article_ids.join(',')}) AND cl_to IN (#{categories_sql}) AND cl_type = 'page' } @mb.repl.query(sql).to_a.first['count'] end def self.perm_request_declined?(username) target_date = @mb.today - 90 links = [] dates_to_fetch = (target_date..@mb.today).select { |d| d.day == target_date.day || d.day == @mb.today.day }.uniq(&:month) dates_to_fetch.each do |date| key = "#{Date::MONTHNAMES[date.month]} #{date.year}" page = @mb.get("Wikipedia:Requests for permissions/Denied/#{key}") next unless page # Regexp.escape may break with other encodings username = username.force_encoding('utf-8') decline_days = page.split(/==\s*\w+\s+/i) decline_days.each do |decline_day| day_number = decline_day.scan(/^(\d+)\s*==/).flatten[0].to_i next if day_number == 0 decline_day_date = @mb.parse_date("#{date.year}-#{date.month}-#{day_number}") matches = decline_day.scan(/\{\{Usercheck.*\|#{Regexp.escape(username).descore}}}.*Autopatrolled\]\]/i)[0] return true if matches && decline_day_date >= target_date end end false end # Get the usernames and edit counts of users who have created a page in the past month def self.page_creators # Cache so this can be re-called without repeating the query return @page_creators if @page_creators sql = %{ SELECT DISTINCT(user_name), actor_id, user_editcount FROM user LEFT JOIN actor ON actor_user = user_id LEFT JOIN recentchanges ON rc_actor = actor_id LEFT JOIN page ON rc_cur_id = page_id WHERE rc_timestamp > #{@mb.db_date(@mb.now - 3)} AND rc_namespace = 0 AND rc_bot = 0 AND rc_new = 1 AND page_is_redirect = 0 AND NOT EXISTS ( SELECT 1 FROM user_groups WHERE ug_user = user_id AND ( ug_group = 'autoreviewer' OR ug_group = 'sysop' ) ) } @page_creators = @mb.repl_query(sql).to_a end end AutopatrolledCandidates.run
MusikAnimal/MusikBot
tasks/autopatrolled_candidates.rb
Ruby
apache-2.0
12,205
package org.jboss.jandex.test.util; import org.jboss.jandex.Index; import org.jboss.jandex.IndexReader; import javax.management.JMException; import javax.management.MBeanServer; import javax.management.ObjectName; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.management.ManagementFactory; public class LoadIndexAndDumpHeap { public static void main(String[] args) throws IOException, JMException { if (args.length != 2) { printUsage(); return; } File indexFile = new File(args[0]); long start = System.currentTimeMillis(); Index index = new IndexReader(new FileInputStream(indexFile)).read(); long time = System.currentTimeMillis() - start; dumpHeap(args[1], true); System.out.println("Reading " + index + " took " + time + "ms"); } private static void printUsage() { System.out.println("Usage: LoadIndexAndDumpHeap <index file name> <heap dump file name>"); } private static void dumpHeap(String filePath, boolean live) throws JMException { MBeanServer jmx = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("com.sun.management:type=HotSpotDiagnostic"); jmx.invoke(name, "dumpHeap", new Object[]{filePath, live}, new String[]{String.class.getName(), boolean.class.getName()}); } }
wildfly/jandex
src/test/java/org/jboss/jandex/test/util/LoadIndexAndDumpHeap.java
Java
apache-2.0
1,432
/** * Copyright 2014 Simeon GIROUSSE * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gote.ui.tournament; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import com.gote.AppUtil; import com.gote.action.tournament.ExportTournamentButton; import com.gote.action.tournament.UpdateResultsButton; import com.gote.pojo.Tournament; import com.gote.ui.home.HomeUI; import com.gote.util.tournament.TournamentUtil; /** * * UI in charge of managing a selected tournament and to export it * * @author SGirousse */ public class TournamentUI extends JFrame implements WindowListener { /** Auto-generated UID */ private static final long serialVersionUID = -3204049783640113974L; /** Reference to the main window */ private HomeUI homeUI; /** Tournament managed */ private Tournament tournament; /** Log Area */ // private JTextArea jTextAreaLog; /** * Default constructor * * @param pHomeUI reference to the main window * @param pTournament Tournament selected/created */ public TournamentUI(HomeUI pHomeUI, Tournament pTournament) { super(); homeUI = pHomeUI; tournament = pTournament; build(); } /** * Build the JFrame */ private void build() { setTitle(AppUtil.buildWindowTitle(TournamentUtil.WINDOW_TITLE, tournament.getTitle())); ImageIcon img = new ImageIcon(AppUtil.APP_ICON_PATH); setIconImage(img.getImage()); setSize(800, 700); setLocationRelativeTo(null); setResizable(false); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setContentPane(buildContentPanel()); addWindowListener(this); // pack(); } /** * Build the panel * * @return JPanel */ private JPanel buildContentPanel() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); // jTextAreaLog = new JTextArea(); // jTextAreaLog.setLineWrap(true); // jTextAreaLog.setWrapStyleWord(true); // JScrollPane jScrollPane = new JScrollPane(jTextAreaLog); // jScrollPane.setPreferredSize(new Dimension(620, 300)); // jScrollPane.setMaximumSize(new Dimension(620, 300)); // jScrollPane.setMinimumSize(new Dimension(620, 300)); JButton jButtonUpdate = new JButton(new UpdateResultsButton(this, tournament, TournamentUtil.BUTTON_UPDATE_LABEL)); JButton jButtonExport = new JButton(new ExportTournamentButton(tournament, TournamentUtil.BUTTON_EXPORT_LABEL)); // JButton jButtonAddToClip = new // JButton("<html><center>Copier dans le presse-papier</center></html>"); // JPanel jPanelLogs = new JPanel(); // jPanelLogs.setLayout(new BoxLayout(jPanelLogs, BoxLayout.LINE_AXIS)); // jPanelLogs.setPreferredSize(new Dimension(750, 350)); // jPanelLogs.setMaximumSize(new Dimension(750, 350)); // jPanelLogs.setMinimumSize(new Dimension(750, 350)); // jPanelLogs.setBorder(BorderFactory.createTitledBorder("Logs")); // jPanelLogs.add(jScrollPane); // jPanelLogs.add(jButtonAddToClip); JPanel jPanelButtons = new JPanel(); jPanelButtons.add(jButtonUpdate); jPanelButtons.add(jButtonExport); panel.add(jPanelButtons); // panel.add(jPanelLogs); return panel; } // public JTextArea getJTextAreaLog() { // return jTextAreaLog; // } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { homeUI.setVisible(true); } @Override public void windowClosing(WindowEvent e) { int choice = JOptionPane.showConfirmDialog(this, TournamentUtil.CLOSE_WINDOW_MSG, TournamentUtil.CLOSE_WINDOW_TITLE, JOptionPane.YES_NO_OPTION); if (choice == JOptionPane.YES_OPTION) { this.dispose(); } } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } }
SGirousse/GOTE
src/com/gote/ui/tournament/TournamentUI.java
Java
apache-2.0
4,871
package net.community.chest.net.proto.text.imap4; import net.community.chest.mail.address.MessageAddressType; /** * <P>Copyright 2007 as per GPLv2</P> * * <P>This interface is used to report intermediate FETCH response parsing * results. In general, if a non-zero return value is returned, then parsing * stops immediately (causing an {@link java.io.IOException} at the "fetch" call). * <B>Note</B>: the results of stoping the parsing in this way are undefined !!!</P> * * @author Lyor G. * @since Sep 20, 2007 10:13:06 AM */ public interface IMAP4FetchResponseHandler { /** * Called to inform about the start/end of a sequence of calls regarding fetched information about the specified message. * @param msgSeqNo message sequence number * @param fStarting if TRUE, then sequence of calls is about to start, else it has ended (and a new message may start) * @return 0 if OK to continue parsing */ int handleMsgResponseState (int msgSeqNo, boolean fStarting); /** * Called to handle the UID response value * @param msgSeqNo message sequence number * @param msgUID UID value * @return 0 if OK to continue parsing */ int handleUID (int msgSeqNo, long msgUID); /** * Special message part ID used to report top-level message ENVELOPE related information */ public static final String ENVELOPE_MSG_PART_ID="0"; public static final char[] ENVELOPE_MSG_PART_IDChars=ENVELOPE_MSG_PART_ID.toCharArray(); /** * Called to inform about the start/end of a message part data stage * @param msgSeqNo message sequence number * @param msgPart shows the sub-part for which the data is starting/ending - if non-"0" then it is an embedded message * @param fStarting if TRUE, then responses are about to start, otherwise they have ended * @return 0 if OK to continue parsing */ int handleMsgPartStage (int msgSeqNo, String msgPart, boolean fStarting); /** * Called to inform about the size (in octets) of a message part * @param msgSeqNo message sequence number * @param msgPart shows the sub-part for which the size is reported - if "0" then it is the total message size * @param partSize size (in octets) of reported message part * @return 0 if OK to continue parsing */ int handleMsgPartSize (int msgSeqNo, String msgPart, long partSize); /** * Called to inform about a message part header data * @param msgSeqNo message sequence number * @param msgPart if non-"0" then shows the sub-part for which the header is supplied - used * mainly for embedded messages. Otherwise, it is the ENVELOPE of the main message * @param hdrName name of header (Note: including a terminating ':') * @param attrName name of a sub-attribute (may be NULL/empty for headers that have no sub-attribute) * @param attrValue header attribute value data (may be null/empty for attributes that have only a name, but no value) * @return 0 if OK to continue parsing */ int handleMsgPartHeader (int msgSeqNo, String msgPart, String hdrName, String attrName, String attrValue); /** * Called to inform about an envelope address data * @param msgSeqNo message sequence number * @param msgPart if non-"0" then shows the sub-part for which the address is supplied - used * mainly for embedded messages. Otherwise, it is the ENVELOPE of the main message * @param addrType address type ("From:/To:/...") * @param dispName display name part of the address (may be null/empty) * @param addrVal e-mail address part * @return 0 if OK to continue parsing */ int handleMsgPartAddress (int msgSeqNo, String msgPart, MessageAddressType addrType, String dispName, String addrVal); /** * Called to inform about the start of a flags stage * @param msgSeqNo message sequence number * @param fStarting if TRUE, then FLAGS responses are about to start, otherwise they have ended * @return 0 if OK to continue parsing */ int handleFlagsStage (int msgSeqNo, boolean fStarting); /** * Called to inform about a flag value * @param msgSeqNo message sequence number * @param flagValue flag value string * @return 0 if OK to continue parsing */ int handleFlagValue (int msgSeqNo, String flagValue); /** * Called to inform about an INTERNALDATE value * @param msgSeqNo message sequence number * @param dateValue date/time value as received from the server - see RFC2060 as to its format * @return 0 if OK to continue parsing */ int handleInternalDate (int msgSeqNo, String dateValue); /** * Called to inform about the start/end of a message part data * @param msgSeqNo message sequence number * @param msgPart if non-"0" then shows the sub-part for which the data is starting/ending * @param fStarting if TRUE, then data calls are about to start, otherwise they have ended * @return 0 if OK to continue parsing */ int handlePartDataStage (int msgSeqNo, String msgPart, boolean fStarting); /** * Called to inform about a buffer of data belonging to a message part * @param msgSeqNo message sequence number * @param msgPart if non-"0" then shows the sub-part for which the data is starting/ending * @param bData data buffer in which returned data resides * @param nOffset offset in data buffer where message part data starts * @param nLen size of valid data in buffer (starting at specified offset) * @return 0 if OK to continue parsing */ int handlePartData (int msgSeqNo, String msgPart, byte[] bData, int nOffset, int nLen); }
lgoldstein/communitychest
chest/net/imap4/src/main/java/net/community/chest/net/proto/text/imap4/IMAP4FetchResponseHandler.java
Java
apache-2.0
5,720
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.imagebuilder.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/GetImageRecipe" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetImageRecipeResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The request ID that uniquely identifies this request. * </p> */ private String requestId; /** * <p> * The image recipe object. * </p> */ private ImageRecipe imageRecipe; /** * <p> * The request ID that uniquely identifies this request. * </p> * * @param requestId * The request ID that uniquely identifies this request. */ public void setRequestId(String requestId) { this.requestId = requestId; } /** * <p> * The request ID that uniquely identifies this request. * </p> * * @return The request ID that uniquely identifies this request. */ public String getRequestId() { return this.requestId; } /** * <p> * The request ID that uniquely identifies this request. * </p> * * @param requestId * The request ID that uniquely identifies this request. * @return Returns a reference to this object so that method calls can be chained together. */ public GetImageRecipeResult withRequestId(String requestId) { setRequestId(requestId); return this; } /** * <p> * The image recipe object. * </p> * * @param imageRecipe * The image recipe object. */ public void setImageRecipe(ImageRecipe imageRecipe) { this.imageRecipe = imageRecipe; } /** * <p> * The image recipe object. * </p> * * @return The image recipe object. */ public ImageRecipe getImageRecipe() { return this.imageRecipe; } /** * <p> * The image recipe object. * </p> * * @param imageRecipe * The image recipe object. * @return Returns a reference to this object so that method calls can be chained together. */ public GetImageRecipeResult withImageRecipe(ImageRecipe imageRecipe) { setImageRecipe(imageRecipe); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRequestId() != null) sb.append("RequestId: ").append(getRequestId()).append(","); if (getImageRecipe() != null) sb.append("ImageRecipe: ").append(getImageRecipe()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetImageRecipeResult == false) return false; GetImageRecipeResult other = (GetImageRecipeResult) obj; if (other.getRequestId() == null ^ this.getRequestId() == null) return false; if (other.getRequestId() != null && other.getRequestId().equals(this.getRequestId()) == false) return false; if (other.getImageRecipe() == null ^ this.getImageRecipe() == null) return false; if (other.getImageRecipe() != null && other.getImageRecipe().equals(this.getImageRecipe()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRequestId() == null) ? 0 : getRequestId().hashCode()); hashCode = prime * hashCode + ((getImageRecipe() == null) ? 0 : getImageRecipe().hashCode()); return hashCode; } @Override public GetImageRecipeResult clone() { try { return (GetImageRecipeResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-imagebuilder/src/main/java/com/amazonaws/services/imagebuilder/model/GetImageRecipeResult.java
Java
apache-2.0
5,255
package org.vyhlidka.homeautomation.endpoint; import org.apache.commons.lang3.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.vyhlidka.homeautomation.domain.Room; import org.vyhlidka.homeautomation.repo.RoomRepository; import java.util.List; /** * Created by lucky on 18.12.16. */ @RestController @RequestMapping(value = "/rooms", produces = MediaType.APPLICATION_JSON_VALUE) public class RoomEndpoint { private final RoomRepository roomRepository; @Autowired public RoomEndpoint(final RoomRepository roomRepository) { Validate.notNull(roomRepository, "roomRepository can not be null;"); this.roomRepository = roomRepository; } @RequestMapping(method = RequestMethod.GET) public List<Room> getBoilers() { return this.roomRepository.getRooms(); } @RequestMapping("/{id}") public ResponseEntity<Room> getRoom(@PathVariable(name = "id") Integer id) { if (id == null) { return ResponseEntity.badRequest().body(null); } Room r = this.roomRepository.getRoom(id); return ResponseEntity.ok(r); } }
LukasVyhlidka/HomeAutomator
server/src/main/java/org/vyhlidka/homeautomation/endpoint/RoomEndpoint.java
Java
apache-2.0
1,485
package com.mindoo.domino.jna.formula; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Set; import com.mindoo.domino.jna.IAdaptable; import com.mindoo.domino.jna.NotesItem; import com.mindoo.domino.jna.NotesNote; import com.mindoo.domino.jna.NotesTimeDate; import com.mindoo.domino.jna.constants.FormulaAttributes; import com.mindoo.domino.jna.errors.FormulaCompilationError; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.errors.UnsupportedItemValueError; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.internal.ItemDecoder; import com.mindoo.domino.jna.internal.Mem32; import com.mindoo.domino.jna.internal.Mem64; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMCMDSPROC; import com.mindoo.domino.jna.internal.NotesCallbacks.NSFFORMFUNCPROC; import com.mindoo.domino.jna.internal.NotesNativeAPI; import com.mindoo.domino.jna.internal.NotesNativeAPI32; import com.mindoo.domino.jna.internal.NotesNativeAPI64; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMCMDSPROCWin32; import com.mindoo.domino.jna.internal.Win32NotesCallbacks.NSFFORMFUNCPROCWin32; import com.mindoo.domino.jna.internal.handles.DHANDLE; import com.mindoo.domino.jna.internal.handles.DHANDLE32; import com.mindoo.domino.jna.internal.handles.DHANDLE64; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.PlatformUtils; import com.sun.jna.Memory; import com.sun.jna.Pointer; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; /** * Utility class to execute a Domino formula on one or more {@link NotesNote} objects. * * @author Karsten Lehmann */ public class FormulaExecution implements IRecyclableNotesObject, IAdaptable { private String m_formula; private long m_hFormula64; private long m_hCompute64; private int m_hFormula32; private int m_hCompute32; private int m_compiledFormulaLength; private Pointer m_ptrCompiledFormula; private boolean m_preferNotesTimeDates; /** * Creates a new instance. The constructure compiles the formula and throws a {@link FormulaCompilationError}, * if there are any compilation errors * * @param formula formula * @throws FormulaCompilationError if formula has wrong syntax */ public FormulaExecution(String formula) throws FormulaCompilationError { m_formula = formula; Memory formulaName = null; short formulaNameLength = 0; Memory formulaText = NotesStringUtils.toLMBCS(formula, false, false); short formulaTextLength = (short) formulaText.size(); short computeFlags = 0; if (PlatformUtils.is64Bit()) { m_hFormula64 = 0; LongByReference rethFormula = new LongByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI64.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula64 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); LongByReference rethCompute = new LongByReference(); m_ptrCompiledFormula = Mem64.OSLockObject(m_hFormula64); result = NotesNativeAPI64.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute64 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } else { m_hFormula32 = 0; IntByReference rethFormula = new IntByReference(); ShortByReference retFormulaLength = new ShortByReference(); ShortByReference retCompileError = new ShortByReference(); ShortByReference retCompileErrorLine = new ShortByReference(); ShortByReference retCompileErrorColumn = new ShortByReference(); ShortByReference retCompileErrorOffset = new ShortByReference(); ShortByReference retCompileErrorLength = new ShortByReference(); short result = NotesNativeAPI32.get().NSFFormulaCompile(formulaName, formulaNameLength, formulaText, formulaTextLength, rethFormula, retFormulaLength, retCompileError, retCompileErrorLine, retCompileErrorColumn, retCompileErrorOffset, retCompileErrorLength); if (result == INotesErrorConstants.ERR_FORMULA_COMPILATION) { String errMsg = NotesErrorUtils.errToString(result); throw new FormulaCompilationError(result, errMsg, formula, retCompileError.getValue(), retCompileErrorLine.getValue(), retCompileErrorColumn.getValue(), retCompileErrorOffset.getValue(), retCompileErrorLength.getValue()); } NotesErrorUtils.checkResult(result); m_hFormula32 = rethFormula.getValue(); m_compiledFormulaLength = (int) (retFormulaLength.getValue() & 0xffff); IntByReference rethCompute = new IntByReference(); m_ptrCompiledFormula = Mem32.OSLockObject(m_hFormula32); result = NotesNativeAPI32.get().NSFComputeStart(computeFlags, m_ptrCompiledFormula, rethCompute); NotesErrorUtils.checkResult(result); m_hCompute32 = rethCompute.getValue(); NotesGC.__objectCreated(FormulaExecution.class, this); } } @SuppressWarnings("unchecked") @Override public <T> T getAdapter(Class<T> clazz) { checkHandle(); if (clazz == byte[].class) { //return compiled formula as byte array byte[] compiledFormula = m_ptrCompiledFormula.getByteArray(0, m_compiledFormulaLength); return (T) compiledFormula; } return null; } public String getFormula() { return m_formula; } /** * Sets whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @param b true to prefer NotesTimeDate (false by default) */ public void setPreferNotesTimeDates(boolean b) { m_preferNotesTimeDates = b; } /** * Returns whether date/time values returned by the executed formulas should be * returned as {@link NotesTimeDate} instead of being converted to {@link Calendar}. * * @return true to prefer NotesTimeDate */ public boolean isPreferNotesTimeDates() { return m_preferNotesTimeDates; } public String toString() { if (isRecycled()) { return "Compiled formula [recycled, formula="+m_formula+"]"; } else { return "Compiled formula [formula="+m_formula+"]"; } } /** * Convenience method to execute a formula on a single note and return the result as a string.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result as string; if the formula returns a list, we pick the first value * @throws FormulaCompilationError if formula has wrong syntax */ public static String evaluateAsString(String formula, NotesNote note) throws FormulaCompilationError { List<Object> result = evaluate(formula, note); if (result.isEmpty()) return ""; else { return result.get(0).toString(); } } /** * Convenience method to execute a formula on a single note.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance and optimized memory usage.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static List<Object> evaluate(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { List<Object> result = instance.evaluate(note); return result; } finally { instance.recycle(); } } /** * Convenience method to execute a formula on a single note. Provides extended information.<br> * <br> * <b>Please note:<br> * If the same formula should be run * on multiple notes, you should consider to create a shared instance of {@link FormulaExecution} * and run its {@link #evaluate(NotesNote)} method. Then the formula is parsed and compiled only * once, which results in better performance.</b> * * @param formula formula * @param note note * @return computation result * @throws FormulaCompilationError if formula has wrong syntax */ public static FormulaExecutionResult evaluateExt(String formula, NotesNote note) throws FormulaCompilationError { FormulaExecution instance = new FormulaExecution(formula); try { FormulaExecutionResult result = instance.evaluateExt(note); return result; } finally { instance.recycle(); } } private void checkHandle() { if (PlatformUtils.is64Bit()) { if (m_hCompute64==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula64==0) { throw new NotesError(0, "Object already recycled"); } } else { if (m_hCompute32==0) { throw new NotesError(0, "Object already recycled"); } if (m_hFormula32==0) { throw new NotesError(0, "Object already recycled"); } } } private List<Object> parseFormulaResult(Pointer valuePtr, int valueLength) { short dataType = valuePtr.getShort(0); int dataTypeAsInt = (int) (dataType & 0xffff); boolean supportedType = false; if (dataTypeAsInt == NotesItem.TYPE_TEXT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { supportedType = true; } if (!supportedType) { throw new UnsupportedItemValueError("Data type is currently unsupported: "+dataTypeAsInt); } int checkDataType = valuePtr.getShort(0) & 0xffff; Pointer valueDataPtr = valuePtr.share(2); int valueDataLength = valueLength - 2; if (checkDataType!=dataTypeAsInt) { throw new IllegalStateException("Value data type does not meet expected date type: found "+checkDataType+", expected "+dataTypeAsInt); } if (dataTypeAsInt == NotesItem.TYPE_TEXT) { String txtVal = (String) ItemDecoder.decodeTextValue(valueDataPtr, valueDataLength, false); return txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal); } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { List<Object> textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(valueDataPtr, false); return textList==null ? Collections.emptyList() : textList; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { double numVal = ItemDecoder.decodeNumber(valueDataPtr, valueDataLength); return Arrays.asList((Object) Double.valueOf(numVal)); } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { List<Object> numberList = ItemDecoder.decodeNumberList(valueDataPtr, valueDataLength); return numberList==null ? Collections.emptyList() : numberList; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { if (isPreferNotesTimeDates()) { NotesTimeDate td = ItemDecoder.decodeTimeDateAsNotesTimeDate(valueDataPtr, valueDataLength); return td==null ? Collections.emptyList() : Arrays.asList((Object) td); } else { Calendar cal = ItemDecoder.decodeTimeDate(valueDataPtr, valueDataLength); return cal==null ? Collections.emptyList() : Arrays.asList((Object) cal); } } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { if (isPreferNotesTimeDates()) { List<Object> tdValues = ItemDecoder.decodeTimeDateListAsNotesTimeDate(valueDataPtr); return tdValues==null ? Collections.emptyList() : tdValues; } else { List<Object> calendarValues = ItemDecoder.decodeTimeDateList(valueDataPtr); return calendarValues==null ? Collections.emptyList() : calendarValues; } } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { //e.g. returned by formula "@DeleteDocument" return Collections.emptyList(); } else if (dataTypeAsInt == NotesItem.TYPE_ERROR) { if (valueLength>=2) { short formulaErrorCode = valueDataPtr.getShort(0); String errMsg = NotesErrorUtils.errToString(formulaErrorCode); throw new NotesError(formulaErrorCode, "Could not evaluate formula "+m_formula+"\nError: "+errMsg); } else { throw new NotesError(0, "Could not evaluate formula "+m_formula); } } else { throw new UnsupportedItemValueError("Data is currently unsupported: "+dataTypeAsInt); } } /** * Evaluates the formula on a note * * @param note note * @return formula computation result */ public List<Object> evaluate(NotesNote note) { return evaluateExt(note).getValue(); } /** * Evaluates the formula on a note. Provides extended information. * * @param note note to be used as additional variables available to the formula or null * @return formula computation result with flags */ public FormulaExecutionResult evaluateExt(NotesNote note) { checkHandle(); if (note!=null) { if (note.isRecycled()) { throw new NotesError(0, "Note is already recycled"); } } if (PlatformUtils.is64Bit()) { LongByReference rethResult = new LongByReference(); ShortByReference retResultLength = new ShortByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); short result = NotesNativeAPI64.get().NSFComputeEvaluate(m_hCompute64, note==null ? 0 : note.getHandle64(), rethResult, retResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified); NotesErrorUtils.checkResult(result); List<Object> formulaResult = null; long hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem64.OSLockObject(hResult); int valueLength = retResultLength.getValue() & 0xffff; try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem64.OSUnlockObject(hResult); result = Mem64.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } else { IntByReference rethResult = new IntByReference(); ShortByReference retResultLength = new ShortByReference(); IntByReference retNoteMatchesFormula = new IntByReference(); IntByReference retNoteShouldBeDeleted = new IntByReference(); IntByReference retNoteModified = new IntByReference(); short result = NotesNativeAPI32.get().NSFComputeEvaluate(m_hCompute32, note==null ? 0 : note.getHandle32(), rethResult, retResultLength, retNoteMatchesFormula, retNoteShouldBeDeleted, retNoteModified); NotesErrorUtils.checkResult(result); List<Object> formulaResult = null; int hResult = rethResult.getValue(); if (hResult!=0) { Pointer valuePtr = Mem32.OSLockObject(hResult); int valueLength = retResultLength.getValue() & 0xffff; try { formulaResult = parseFormulaResult(valuePtr, valueLength); } finally { Mem32.OSUnlockObject(hResult); result = Mem32.OSMemFree(hResult); NotesErrorUtils.checkResult(result); } } else { throw new IllegalStateException("got a null handle as computation result"); } return new FormulaExecutionResult(formulaResult, retNoteMatchesFormula.getValue()==1, retNoteShouldBeDeleted.getValue()==1, retNoteModified.getValue()==1); } } /** * Formula computation result * * @author Karsten Lehmann */ public static class FormulaExecutionResult { private List<Object> m_result; private boolean m_matchesFormula; private boolean m_shouldBeDeleted; private boolean m_noteModified; public FormulaExecutionResult(List<Object> result, boolean matchesFormula, boolean shouldBeDeleted, boolean noteModified) { m_result = result; m_matchesFormula = matchesFormula; m_shouldBeDeleted = shouldBeDeleted; m_noteModified = noteModified; } public List<Object> getValue() { return m_result; } public boolean matchesFormula() { return m_matchesFormula; } public boolean shouldBeDeleted() { return m_shouldBeDeleted; } public boolean isNoteModified() { return m_noteModified; } } @Override public void recycle() { if (isRecycled()) return; if (PlatformUtils.is64Bit()) { if (m_hCompute64!=0) { short result = NotesNativeAPI64.get().NSFComputeStop(m_hCompute64); NotesErrorUtils.checkResult(result); m_hCompute64=0; } if (m_hFormula64!=0) { Mem64.OSUnlockObject(m_hFormula64); short result = Mem64.OSMemFree(m_hFormula64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula64 = 0; m_ptrCompiledFormula=null; } } else { if (m_hCompute32!=0) { short result = NotesNativeAPI32.get().NSFComputeStop(m_hCompute32); NotesErrorUtils.checkResult(result); m_hCompute32=0; } if (m_hFormula32!=0) { Mem32.OSUnlockObject(m_hFormula32); short result = Mem32.OSMemFree(m_hFormula32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(FormulaExecution.class, this); m_hFormula32 = 0; m_ptrCompiledFormula=null; } } } @Override public boolean isRecycled() { if (PlatformUtils.is64Bit()) { if (m_hFormula64==0) { return true; } } else { if (m_hFormula32==0) { return true; } } return false; } @Override public boolean isNoRecycle() { return false; } @Override public int getHandle32() { return m_hFormula32; } @Override public long getHandle64() { return m_hFormula64; } public DHANDLE getHandle() { if (PlatformUtils.is64Bit()) { return DHANDLE64.newInstance(m_hFormula64); } else { return DHANDLE32.newInstance(m_hFormula32); } } /** * Returns a list of all registered (public) formula functions. Use {@link #getFunctionParameters(String)} * to get a list of function parameters. * * @return functions, e.g. "@Left(" */ public static List<String> getAllFunctions() { List<String> retNames = new ArrayList<>(); NSFFORMFUNCPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMFUNCPROCWin32() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMFUNCPROC() { @Override public short invoke(Pointer ptr) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaFunctions(callback); NotesErrorUtils.checkResult(result); return retNames; } /** * Returns a list of all registered (public) formula commands. Use {@link #getFunctionParameters(String)} * to get a list of command parameters. * * @return commands, e.g. "MailSend" */ public static List<String> getAllCommands() { List<String> retNames = new ArrayList<>(); NSFFORMCMDSPROC callback; if (PlatformUtils.isWin32()) { callback = new NSFFORMCMDSPROCWin32() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } else { callback = new NSFFORMCMDSPROC() { @Override public short invoke(Pointer ptr, short code, IntByReference stopFlag) { String name = NotesStringUtils.fromLMBCS(ptr, -1); retNames.add(name); return 0; } }; } short result = NotesNativeAPI.get().NSFFormulaCommands(callback); NotesErrorUtils.checkResult(result); return retNames; } public static class FormulaAnalyzeResult { private EnumSet<FormulaAttributes> attributes; private FormulaAnalyzeResult(EnumSet<FormulaAttributes> attributes) { this.attributes = attributes; } public Set<FormulaAttributes> getAttributes() { return Collections.unmodifiableSet(this.attributes); } @Override public String toString() { return "FormulaAnalyzeResult [attributes=" + attributes + "]"; } } /** * Scan through the function table (ftable) or keyword table (ktable) * to find parameters of an @ function or an @ command. * * @param formulaName name returned by {@link FormulaExecution#getAllFunctions()}, e.g. "@Left(" * @return function parameters, e.g. "stringToSearch; numberOfChars)stringToSearch; subString)" for the function "@Left(" */ public static List<String> getFunctionParameters(String formulaName) { Memory formulaMem = NotesStringUtils.toLMBCS(formulaName, true); Pointer ptr = NotesNativeAPI.get().NSFFindFormulaParameters(formulaMem); if (ptr==null) { return Collections.emptyList(); } else { //example format for @Middle(: //string; offset; numberchars)string; offset; endstring)string; startString; endstring)string; startString; numberchars) List<String> params = new ArrayList<>(); String paramsConc = NotesStringUtils.fromLMBCS(ptr, -1); StringBuilder sb = new StringBuilder(); for (int i=0; i<paramsConc.length(); i++) { char c = paramsConc.charAt(i); sb.append(c); if (c==')') { params.add(sb.toString()); sb.setLength(0); } } return params; } } /** * Analyzes the @-function * * @return result with flags, e.g. whether the function returns a constant value or is time based */ public FormulaAnalyzeResult analyze() { checkHandle(); DHANDLE hFormula = getHandle(); IntByReference retAttributes = new IntByReference(); ShortByReference retSummaryNamesOffset = new ShortByReference(); short result = NotesNativeAPI.get().NSFFormulaAnalyze(hFormula.getByValue(), retAttributes, retSummaryNamesOffset); NotesErrorUtils.checkResult(result); EnumSet<FormulaAttributes> attributes = FormulaAttributes.toFormulaAttributes(retAttributes.getValue()); return new FormulaAnalyzeResult(attributes); } }
klehmann/domino-jna
domino-jna/src/main/java/com/mindoo/domino/jna/formula/FormulaExecution.java
Java
apache-2.0
24,166
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using DontForgetTheEggs.Core.Common.Exceptions; using Newtonsoft.Json; namespace DontForgetTheEggs.Web.Infrastructure.Validation { public class EggsHandleErrorAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (!(filterContext.Exception is EggsDataException eggsDataException)) { base.OnException(filterContext); return; } filterContext.Controller.ViewData.ModelState.AddModelError("", eggsDataException.Message); filterContext.ExceptionHandled = true; //Note: this code below is very similar to the previous. // Unfortunatly we can't extract it to a base method since the arguments are diferent // ActionExecutingContext vs ResultExecutedContext and their base class ControllerContext // has no Result property so we can set the results //model state is not valid, and we're returning from a GET request if (filterContext.HttpContext.Request.HttpMethod == "GET") { var result = new HttpStatusCodeResult(HttpStatusCode.BadRequest); filterContext.Result = result; } //model state is not valid and we're being requested by an async POST if (filterContext.HttpContext.Request.IsAjaxRequest()) { var result = new ContentResult(); string content = JsonConvert.SerializeObject(filterContext.Controller.ViewData.ModelState, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); result.Content = content; result.ContentType = "application/json"; filterContext.HttpContext.Response.StatusCode = 400; filterContext.Result = result; } //model state is not valid and we're being requested by a POST not async filterContext.Result = new ViewResult { ViewData = filterContext.Controller.ViewData, TempData = filterContext.Controller.TempData }; } } }
kappy/DontForgetTheEggs
src/DontForgetTheEggs.Web/Infrastructure/Validation/EggsHandleErrorAttribute.cs
C#
apache-2.0
2,424
<?php if(!defined('HDPHP_PATH'))EXIT; $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('1','21312312','200','1-3','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('2','21312312','200','1-5','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('3','21312312','200','1-6','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('4','21312312','200','1-4','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('5','21312312','200','2-3','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('6','21312312','200','2-5','1')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('7','21312312','200','14-16','2')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('8','21312312','200','14-18','2')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('9','21312312','200','14-19','2')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('10','21312312','200','15-16','2')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('11','21312312','200','15-19','2')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('12','21312312','200','28-40','3')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('13','21312312','200','28-39','3')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('14','21312312','200','49-51','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('15','21312312','200','49-52','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('16','21312312','200','49-53','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('17','21312312','200','50-54','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('18','21312312','200','50-51','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('19','21312312','200','50-53','4')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('20','21312312','200','63-65','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('21','21312312','200','63-66','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('22','21312312','200','63-67','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('23','21312312','200','64-65','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('24','21312312','200','64-66','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('25','21312312','200','64-68','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('26','21312312','200','64-69','5')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('27','21312312','200','78-80','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('28','21312312','200','78-81','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('29','21312312','200','78-82','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('30','21312312','200','78-83','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('31','21312312','200','79-80','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('32','21312312','200','79-81','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('33','21312312','200','79-82','6')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('34','21312312','200','92-94','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('35','21312312','200','92-95','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('36','21312312','200','92-96','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('37','21312312','200','92-97','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('38','21312312','200','93-94','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('39','21312312','200','93-95','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('40','21312312','200','93-96','7')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('41','32211221','200','107-109','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('42','32211221','200','107-110','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('43','32211221','200','107-111','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('44','32211221','200','107-112','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('45','32211221','200','108-109','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('46','32211221','200','108-110','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('47','32211221','200','108-111','8')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('48','21312312','200','122-123','9')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('49','21312312','200','122-132','9')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('50','21312312','200','122-133','9')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('51','21312312','200','122-134','9')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('52','1221323','200','143-146','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('53','1221323','200','143-147','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('54','1221323','200','143-148','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('55','1221323','200','144-148','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('56','1221323','200','144-149','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('57','1221323','200','145-146','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('58','1221323','200','145-148','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('59','1221323','200','145-149','10')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('60','12321321','200','158-159','11')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('61','12321321','200','158-160','11')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('62','12321321','200','158-161','11')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('63','12321321','200','158-163','11')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('64','2312321','200','172-174','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('65','2312321','200','172-175','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('66','2312321','200','172-176','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('67','2312321','200','173-175','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('68','2312321','200','173-177','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('69','2312321','200','173-178','12')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('70','342222','200','187-189','13')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('71','342222','200','187-191','13')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('72','342222','200','188-190','13')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('73','342222','200','188-192','13')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('74','342222','200','188-193','13')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('75','3242332','200','201-202','14')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('76','3242332','200','201-203','14')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('77','3242332','200','201-204','14')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('78','3242332','200','201-205','14')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('79','2321321','200','215-216','15')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('80','2321321','200','215-217','15')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('81','2321321','200','215-218','15')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('82','2321321','200','215-219','15')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('83','4322232','200','229-230','16')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('84','4322232','200','229-231','16')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('85','4322232','200','229-232','16')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('86','4322232','200','229-233','16')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('87','12312321','200','251-253','17')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('88','12312321','200','251-255','17')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('89','12312321','200','252-254','17')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('90','12312321','200','252-256','17')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('91','12312321','200','252-257','17')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('92','32423213','200','266-267','18')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('93','32423213','200','266-269','18')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('94','32423213','200','266-270','18')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('95','3242','200','291-282','19')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('96','3242','200','280-282','19')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('97','232231','200','300-302','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('98','232231','200','300-303','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('99','232231','200','300-304','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('100','232231','200','301-303','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('101','232231','200','301-304','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('102','232231','200','301-305','20')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('103','453543','200','316-317','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('104','453543','200','316-318','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('105','453543','200','316-319','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('106','453543','200','316-320','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('107','453543','200','315-317','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('108','453543','200','315-319','21')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('109','345343','200','330-331','22')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('110','345343','200','330-332','22')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('111','345343','200','330-334','22')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('112','345343','200','330-335','22')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('113','32434','32767','361-363','23')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('114','234232','200','372-374','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('115','234232','200','372-375','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('116','234232','200','372-376','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('117','234232','200','372-377','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('118','234232','200','373-375','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('119','234232','200','373-376','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('120','234232','200','373-377','24')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('121','345342','200','385-387','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('122','345342','200','385-388','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('123','345342','200','385-389','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('124','345342','200','385-390','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('125','345342','200','386-388','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('126','345342','200','386-389','25')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('127','32434','200','399-400','26')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('128','343243','200','409-411','27')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('129','3224232','200','429-420','28')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('130','3224232','200','429-430','28')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('131','3224232','200','429-432','28')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('132','3224232','200','428-430','28')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('133','3224232','200','428-432','28')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('134','3453535','200','441-443','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('135','3453535','200','441-444','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('136','3453535','200','441-445','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('137','3453535','200','442-444','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('138','3453535','200','442-445','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('139','3453535','200','442-446','29')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('140','2432242','200','455-456','30')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('141','2432242','200','455-457','30')"); $db->exe("REPLACE INTO ".$db_prefix."product (`product_id`,`product_sn`,`product_number`,`goods_attr`,`goods_gid`) VALUES('142','2432242','200','455-459','30')");
ly2513/ymgshop
Backup/20141211014314/shop_product_bk_16.php
PHP
apache-2.0
24,090
# Copyright 2012 NEC Corporation # Copyright 2015 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.core.urlresolvers import reverse from django import http from mox3.mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test DETAIL_URL = 'horizon:admin:networks:ports:detail' NETWORKS_INDEX_URL = reverse('horizon:admin:networks:index') NETWORKS_DETAIL_URL = 'horizon:admin:networks:detail' class NetworkPortTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('network_get', 'port_get', 'is_extension_supported',)}) def test_port_detail(self): self._test_port_detail() @test.create_stubs({api.neutron: ('network_get', 'port_get', 'is_extension_supported',)}) def test_port_detail_with_mac_learning(self): self._test_port_detail(mac_learning=True) def _test_port_detail(self, mac_learning=False): port = self.ports.first() network_id = self.networks.first().id api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(self.ports.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .MultipleTimes().AndReturn(mac_learning) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'allowed-address-pairs') \ .MultipleTimes().AndReturn(False) api.neutron.network_get(IsA(http.HttpRequest), network_id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() res = self.client.get(reverse(DETAIL_URL, args=[port.id])) self.assertTemplateUsed(res, 'horizon/common/_detail.html') self.assertEqual(res.context['port'].id, port.id) @test.create_stubs({api.neutron: ('port_get',)}) def test_port_detail_exception(self): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() res = self.client.get(reverse(DETAIL_URL, args=[port.id])) redir_url = NETWORKS_INDEX_URL self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported',)}) def test_port_create_get(self): self._test_port_create_get() @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported',)}) def test_port_create_get_with_mac_learning(self): self._test_port_create_get(mac_learning=True) def _test_port_create_get(self, mac_learning=False, binding=False): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() url = reverse('horizon:admin:networks:addport', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/ports/create.html') @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported', 'port_create',)}) def test_port_create_post(self): self._test_port_create_post() @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported', 'port_create',)}) def test_port_create_post_with_mac_learning(self): self._test_port_create_post(mac_learning=True, binding=False) def _test_port_create_post(self, mac_learning=False, binding=False): network = self.networks.first() port = self.ports.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = \ port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_create(IsA(http.HttpRequest), tenant_id=network.tenant_id, network_id=network.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndReturn(port) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'network_name': network.name, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:addport', args=[port.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse(NETWORKS_DETAIL_URL, args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'port_create', 'is_extension_supported',)}) def test_port_create_post_exception(self): self._test_port_create_post_exception() @test.create_stubs({api.neutron: ('network_get', 'port_create', 'is_extension_supported',)}) def test_port_create_post_exception_with_mac_learning(self): self._test_port_create_post_exception(mac_learning=True) def _test_port_create_post_exception(self, mac_learning=False, binding=False): network = self.networks.first() port = self.ports.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_create(IsA(http.HttpRequest), tenant_id=network.tenant_id, network_id=network.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'network_name': network.name, 'name': port.name, 'admin_state': port.admin_state_up, 'mac_state': True, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_learning_enabled'] = True url = reverse('horizon:admin:networks:addport', args=[port.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse(NETWORKS_DETAIL_URL, args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_update_get(self): self._test_port_update_get() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_update_get_with_mac_learning(self): self._test_port_update_get(mac_learning=True) def _test_port_update_get(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/ports/update.html') @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post(self): self._test_port_update_post() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_with_mac_learning(self): self._test_port_update_post(mac_learning=True) def _test_port_update_post(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_update(IsA(http.HttpRequest), port.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndReturn(port) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'port_id': port.id, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.post(url, form_data) redir_url = reverse(NETWORKS_DETAIL_URL, args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_exception(self): self._test_port_update_post_exception() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_exception_with_mac_learning(self): self._test_port_update_post_exception(mac_learning=True, binding=False) def _test_port_update_post_exception(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_update(IsA(http.HttpRequest), port.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'port_id': port.id, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.post(url, form_data) redir_url = reverse(NETWORKS_DETAIL_URL, args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'show_network_ip_availability', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete(self): self._test_port_delete() @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'show_network_ip_availability', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete_with_mac_learning(self): self._test_port_delete(mac_learning=True) def _test_port_delete(self, mac_learning=False): port = self.ports.first() network_id = port.network_id api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'ports__delete__%s' % port.id} url = reverse(NETWORKS_DETAIL_URL, args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'show_network_ip_availability', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete_exception(self): self._test_port_delete_exception() @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'show_network_ip_availability', 'is_extension_supported', 'list_dhcp_agent_hosting_networks')}) def test_port_delete_exception_with_mac_learning(self): self._test_port_delete_exception(mac_learning=True) def _test_port_delete_exception(self, mac_learning=False): port = self.ports.first() network_id = port.network_id api.neutron.port_delete(IsA(http.HttpRequest), port.id)\ .AndRaise(self.exceptions.neutron) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'network-ip-availability').AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'ports__delete__%s' % port.id} url = reverse(NETWORKS_DETAIL_URL, args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url)
wolverineav/horizon
openstack_dashboard/dashboards/admin/networks/ports/tests.py
Python
apache-2.0
20,198
/* * Copyright 2015 Charles University in Prague * Copyright 2015 Vojtech Horky * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cz.cuni.mff.d3s.spl.formula; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import cz.cuni.mff.d3s.spl.Formula; import cz.cuni.mff.d3s.spl.Interpretation; import cz.cuni.mff.d3s.spl.Result; import cz.cuni.mff.d3s.spl.tests.InterpretationForTests; @Ignore public class LogicOpTestBase { protected Interpretation interpretation; protected final Formula leftSubformula; protected final Formula rightSubformula; protected final Result expectedResult; protected Formula constructedFormula; public LogicOpTestBase(final Formula left, final Formula right, final Result result) { expectedResult = result; leftSubformula = left; rightSubformula = right; } @Before public void setupInterpretation() { interpretation = new InterpretationForTests(); } @Test public void evaluationTest() { assertEquals(expectedResult, constructedFormula.evaluate(InterpretationForTests.DEFAULT_SIGNIFICANCE_LEVEL)); } }
D-iii-S/spl-evaluation-java
src/test-java/cz/cuni/mff/d3s/spl/formula/LogicOpTestBase.java
Java
apache-2.0
1,647
/******************************************************************************* * Copyright 2011 Google Inc. All Rights Reserved. * * 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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package nl.sense_os.commonsense.main.client.logout; import java.util.logging.Logger; import nl.sense_os.commonsense.common.client.communication.CommonSenseApi; import nl.sense_os.commonsense.common.client.communication.SessionManager; import nl.sense_os.commonsense.main.client.MainClientFactory; import nl.sense_os.commonsense.main.client.MainEntryPoint; import com.google.gwt.activity.shared.AbstractActivity; import com.google.gwt.event.shared.EventBus; import com.google.gwt.http.client.Request; import com.google.gwt.http.client.RequestCallback; import com.google.gwt.http.client.Response; import com.google.gwt.user.client.ui.AcceptsOneWidget; /** * Activities are started and stopped by an ActivityManager associated with a container Widget. */ public class LogoutActivity extends AbstractActivity implements LogoutView.Presenter { private static final Logger LOG = Logger.getLogger(LogoutActivity.class.getName()); /** * Used to obtain views, eventBus, placeController. Alternatively, could be injected via GIN. */ private final MainClientFactory clientFactory; public LogoutActivity(LogoutPlace place, MainClientFactory clientFactory) { this.clientFactory = clientFactory; } /** * Requests logout of session from CommonSense */ private void logout() { LOG.finest("Log out"); RequestCallback callback = new RequestCallback() { @Override public void onError(Request request, Throwable exception) { onLogoutError(-1, exception); } @Override public void onResponseReceived(Request request, Response response) { onLogoutResponse(response); } }; CommonSenseApi.logout(callback); } /** * Handles response to logout request * * @param response */ private void onLogoutResponse(Response response) { if (Response.SC_OK == response.getStatusCode()) { onLogoutSuccess(); } else { onLogoutError(response.getStatusCode(), new Throwable(response.getStatusText())); } } /** * Handles successful logout */ private void onLogoutSuccess() { SessionManager.removeSessionId(); MainEntryPoint.goToLoginPage(); } /** * Handles failed logout requests * * @param code * Error code * @param error * Error message */ private void onLogoutError(int code, Throwable error) { // TODO Handle logout failure LOG.warning("Logout failure! Code: " + code + " " + error); onLogoutSuccess(); } @Override public void start(AcceptsOneWidget containerWidget, EventBus eventBus) { LOG.info("Start 'logout' activity"); // show view LogoutView view = clientFactory.getLogoutView(); view.setPresenter(this); containerWidget.setWidget(view.asWidget()); // log out logout(); } }
senseobservationsystems/commonsense-frontend
src/nl/sense_os/commonsense/main/client/logout/LogoutActivity.java
Java
apache-2.0
3,497
//===----------------------------------------------------------------------===// // // Peloton // // numeric_value.cpp // // Identification: src/backend/type/numeric_value.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "type/bigint_type.h" #include "type/value_factory.h" namespace peloton { namespace type { #define BIGINT_COMPARE_FUNC(OP) \ switch (right.GetTypeId()) { \ case TypeId::TINYINT: \ return GetCmpBool(left.value_.bigint OP right.GetAs<int8_t>()); \ case TypeId::SMALLINT: \ return GetCmpBool(left.value_.bigint OP right.GetAs<int16_t>()); \ case TypeId::INTEGER: \ case TypeId::PARAMETER_OFFSET: \ return GetCmpBool(left.value_.bigint OP right.GetAs<int32_t>()); \ case TypeId::BIGINT: \ return GetCmpBool(left.value_.bigint OP right.GetAs<int64_t>()); \ case TypeId::DECIMAL: \ return GetCmpBool(left.value_.bigint OP right.GetAs<double>()); \ case TypeId::VARCHAR: { \ auto r_value = right.CastAs(TypeId::BIGINT); \ return GetCmpBool(left.value_.bigint OP r_value.GetAs<int64_t>()); \ } \ default: \ break; \ } // SWITCH #define BIGINT_MODIFY_FUNC(METHOD, OP) \ switch (right.GetTypeId()) { \ case TypeId::TINYINT: \ return METHOD<int64_t, int8_t>(left, right); \ case TypeId::SMALLINT: \ return METHOD<int64_t, int16_t>(left, right); \ case TypeId::INTEGER: \ case TypeId::PARAMETER_OFFSET: \ return METHOD<int64_t, int32_t>(left, right); \ case TypeId::BIGINT: \ return METHOD<int64_t, int64_t>(left, right); \ case TypeId::DECIMAL: \ return ValueFactory::GetDecimalValue( \ left.value_.bigint OP right.GetAs<double>()); \ case TypeId::VARCHAR: { \ auto r_value = right.CastAs(TypeId::BIGINT); \ return METHOD<int64_t, int64_t>(left, r_value); \ } \ default: \ break; \ } // SWITCH BigintType::BigintType() : IntegerParentType(BIGINT) { } bool BigintType::IsZero(const Value& val) const { return (val.value_.bigint == 0); } Value BigintType::Add(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); BIGINT_MODIFY_FUNC(AddValue, +); throw Exception("type error"); } Value BigintType::Subtract(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); BIGINT_MODIFY_FUNC(SubtractValue, -); throw Exception("type error"); } Value BigintType::Multiply(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); BIGINT_MODIFY_FUNC(MultiplyValue, *); throw Exception("type error"); } Value BigintType::Divide(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); if (right.IsZero()) { throw Exception(EXCEPTION_TYPE_DIVIDE_BY_ZERO, "Division by zero on right-hand side"); } BIGINT_MODIFY_FUNC(DivideValue, /); throw Exception("type error"); } Value BigintType::Modulo(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return left.OperateNull(right); if (right.IsZero()) { throw Exception(EXCEPTION_TYPE_DIVIDE_BY_ZERO, "Division by zero on right-hand side"); } switch (right.GetTypeId()) { case TypeId::TINYINT: return ModuloValue<int64_t, int8_t>(left, right); case TypeId::SMALLINT: return ModuloValue<int64_t, int16_t>(left, right); case TypeId::INTEGER: case TypeId::PARAMETER_OFFSET: return ModuloValue<int64_t, int32_t>(left, right); case TypeId::BIGINT: return ModuloValue<int64_t, int64_t>(left, right); case TypeId::DECIMAL: return ValueFactory::GetDecimalValue( ValMod(left.value_.bigint, right.GetAs<double>())); case TypeId::VARCHAR: { auto r_value = right.CastAs(TypeId::BIGINT); return ModuloValue<int64_t, int64_t>(left, r_value); } default: break; } throw Exception("type error"); } Value BigintType::Sqrt(const Value& val) const { PL_ASSERT(val.CheckInteger()); if (val.IsNull()) return ValueFactory::GetDecimalValue(PELOTON_DECIMAL_NULL); if (val.value_.bigint < 0) { throw Exception(EXCEPTION_TYPE_DECIMAL, "Cannot take square root of a negative number."); } return ValueFactory::GetDecimalValue(sqrt(val.value_.bigint)); } Value BigintType::OperateNull(const Value& left UNUSED_ATTRIBUTE, const Value &right) const { switch (right.GetTypeId()) { case TypeId::TINYINT: case TypeId::SMALLINT: case TypeId::INTEGER: case TypeId::PARAMETER_OFFSET: case TypeId::BIGINT: return ValueFactory::GetBigIntValue((int64_t) PELOTON_INT64_NULL); case TypeId::DECIMAL: return ValueFactory::GetDecimalValue((double) PELOTON_DECIMAL_NULL); default: break; } throw Exception("type error"); } CmpBool BigintType::CompareEquals(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(==); throw Exception("type error"); } CmpBool BigintType::CompareNotEquals(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(!=); throw Exception("type error"); } CmpBool BigintType::CompareLessThan(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(<); throw Exception("type error"); } CmpBool BigintType::CompareLessThanEquals(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(<=); throw Exception("type error"); } CmpBool BigintType::CompareGreaterThan(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(>); throw Exception("type error"); } CmpBool BigintType::CompareGreaterThanEquals(const Value& left, const Value &right) const { PL_ASSERT(left.CheckInteger()); PL_ASSERT(left.CheckComparable(right)); if (left.IsNull() || right.IsNull()) return CMP_NULL; BIGINT_COMPARE_FUNC(>=); throw Exception("type error"); } std::string BigintType::ToString(const Value& val) const { PL_ASSERT(val.CheckInteger()); if (val.IsNull()) return "bigint_null"; return std::to_string(val.value_.bigint); } size_t BigintType::Hash(const Value& val) const { PL_ASSERT(val.CheckInteger()); return std::hash<int64_t> { }(val.value_.bigint); } void BigintType::HashCombine(const Value& val, size_t &seed) const { val.hash_combine<int64_t>(seed, val.value_.bigint); } void BigintType::SerializeTo(const Value& val, SerializeOutput &out) const { out.WriteLong(val.value_.bigint); } void BigintType::SerializeTo(const Value& val, char *storage, bool inlined UNUSED_ATTRIBUTE, AbstractPool *pool UNUSED_ATTRIBUTE) const { *reinterpret_cast<int64_t *>(storage) = val.value_.bigint; } // Deserialize a value of the given type from the given storage space. Value BigintType::DeserializeFrom(const char *storage , const bool inlined UNUSED_ATTRIBUTE, AbstractPool *pool UNUSED_ATTRIBUTE) const{ int64_t val = *reinterpret_cast<const int64_t *>(storage); return Value(type_id_, val); } Value BigintType::DeserializeFrom(SerializeInput &in UNUSED_ATTRIBUTE, AbstractPool *pool UNUSED_ATTRIBUTE) const{ return Value(type_id_, in.ReadLong()); } Value BigintType::Copy(const Value& val) const { return ValueFactory::GetBigIntValue(val.value_.bigint); } Value BigintType::CastAs(const Value& val, const TypeId type_id) const { switch (type_id) { case TypeId::TINYINT: { if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); if (val.GetAs<int64_t>() > PELOTON_INT8_MAX || val.GetAs<int64_t>() < PELOTON_INT8_MIN) throw Exception(EXCEPTION_TYPE_OUT_OF_RANGE, "Numeric value out of range."); return ValueFactory::GetTinyIntValue((int8_t) val.GetAs<int64_t>()); } case TypeId::SMALLINT: { if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); if (val.GetAs<int64_t>() > PELOTON_INT16_MAX || val.GetAs<int64_t>() < PELOTON_INT16_MIN) throw Exception(EXCEPTION_TYPE_OUT_OF_RANGE, "Numeric value out of range."); return ValueFactory::GetSmallIntValue((int16_t) val.GetAs<int64_t>()); } case TypeId::INTEGER: case TypeId::PARAMETER_OFFSET: { if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); if (val.GetAs<int64_t>() > PELOTON_INT32_MAX || val.GetAs<int64_t>() < PELOTON_INT32_MIN) throw Exception(EXCEPTION_TYPE_OUT_OF_RANGE, "Numeric value out of range."); return Value(type_id, (int32_t) val.GetAs<int64_t>()); } case TypeId::BIGINT: { if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); return val.Copy(); } case TypeId::DECIMAL: { if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); return ValueFactory::GetDecimalValue((double) val.GetAs<int64_t>()); } case TypeId::VARCHAR: if (val.IsNull()) return ValueFactory::GetNullValueByType(type_id); return ValueFactory::GetVarcharValue(val.ToString()); default: break; } throw Exception( Type::GetInstance(val.GetTypeId())->ToString() + " is not coercable to " + Type::GetInstance(type_id)->ToString()); } } // namespace type } // namespace peloton
prashasthip/peloton
src/type/bigint_type.cpp
C++
apache-2.0
10,496
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>BITSO 4.0</title> <?php $this->load->view('common');?> <script src="<?php echo base_url();?>util/bitso/bower_components/jquery/dist/jquery.min.js"></script> </head> <body> <div id="wrapper"> <?php $this->load->view('left2');?> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"><?php if(isset($id) && $id>0){echo 'Edit';}else{echo 'Add';} ?> NextCategory</h1> </div> <!-- /.col-lg-12 --> </div> <!-- /.row --> <div class="panel-body"> <div class="row"> <div class="col-lg-6"> <form action="<?php echo site_url('Ial_admin/IAL_category/toadd_nextcategory') ?>" method="post"> <table> <input name="ic_id" value="<?php echo isset($ic_id)?$ic_id:0; ?>" type="hidden"/> <input name="id" value="<?php echo isset($id)?$id:0; ?>" type="hidden"/> <div class="input-append date"> <label>nextcate_name </label> <input type="text" name="nc_name" value="<?php echo isset($next['nc_name'])?$next['nc_name']:'';?>"/> </div><br> <div class="input-append date"> <label></label> <input type="SUBMIT" value="SUBMIT"/> </div> </table> </form> </div> </div> <!-- /.row --> </div> <!-- /#page-wrapper --> </div> <?php $this->load->view('foot'); ?> </body> </html>
lenovowebcto/bitso4.0
application/views/ial/admin/category/addnextcategory.php
PHP
apache-2.0
1,868
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import xlrd import xlwt import datetime def request(): sheet = xlrd.open_workbook(os.path.join('E:/w/', '修改工单.xls')).sheet_by_index(0) nRow = sheet.nrows nCol = sheet.ncols title = [] rowDatas = {} for i in range(nRow): # 标题 if(i == 0): for j in range(nCol): title.append(sheet.cell_value(i, j)) else: oneItem = [] for j in range(nCol): oneItem.append(sheet.cell_value(i, j)) key = sheet.cell_value(i, 9) rowData = rowDatas.get(key) if rowData is None: rowData = [] rowData.append(oneItem) rowDatas[key] = rowData else: rowData.append(oneItem) for key, rowData in rowDatas.items(): if(len(rowData) == 1): for oneItem in rowData: oneItem[25] = '未倒回' else: rowData.sort(key = lambda e : e[1], reverse=False) rowData[0][25] = '未倒回' rowData[len(rowData)-1][25] = '未倒回' for i in range(len(rowData)-1): if rowData[i][15] == rowData[i + 1][16]: orgDate = datetime.datetime.strptime('{:.0f}'.format(rowData[i][1]), '%Y%m%d') targetDate = datetime.datetime.strptime('{:.0f}'.format(rowData[i + 1][1]), '%Y%m%d') diffDay = targetDate - orgDate if diffDay.days >= 0 and diffDay.days <= 5: rowData[i][25] = '已倒回' rowData[i + 1][25] = '已倒回' else: rowData[i][25] = '超时倒回' rowData[i + 1][25] = '超时倒回' writeBook = xlwt.Workbook() writeSheet = writeBook.add_sheet('Sheet0') for i in range(len(title)): writeSheet.write(0, i, title[i]) # 写数据到一个文件 rowIndex = 1 for key, rowData in rowDatas.items(): for oneItem in rowData: for j in range(nCol): writeSheet.write(rowIndex, j, oneItem[j]) rowIndex += 1 writeBook.save(os.path.join('E:/w/', '修改工单-结果.xlsx')) if __name__ == '__main__': request()
tiandizhiguai/test
src/main/java/com/test/python/data_test4.py
Python
apache-2.0
2,395
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.debugger.jdi; import com.intellij.Patches; import com.intellij.debugger.engine.DebuggerUtils; import com.intellij.debugger.engine.jdi.VirtualMachineProxy; import com.intellij.debugger.impl.DebuggerUtilsEx; import com.intellij.openapi.util.Ref; import com.intellij.util.ReflectionUtil; import com.intellij.util.ThrowableConsumer; import com.intellij.util.containers.ContainerUtil; import com.sun.jdi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.org.objectweb.asm.*; import org.jetbrains.org.objectweb.asm.Type; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author egor */ public class MethodBytecodeUtil { private MethodBytecodeUtil() { } /** * Allows to use ASM MethodVisitor with jdi method bytecode */ public static void visit(Method method, MethodVisitor methodVisitor, boolean withLineNumbers) { visit(method, method.bytecodes(), methodVisitor, withLineNumbers); } public static void visit(Method method, long maxOffset, MethodVisitor methodVisitor, boolean withLineNumbers) { if (maxOffset > 0) { // need to keep the size, otherwise labels array will not be initialized correctly byte[] originalBytecodes = method.bytecodes(); byte[] bytecodes = originalBytecodes; if (maxOffset < originalBytecodes.length) { bytecodes = new byte[originalBytecodes.length]; System.arraycopy(originalBytecodes, 0, bytecodes, 0, (int)maxOffset); } visit(method, bytecodes, methodVisitor, withLineNumbers); } } public static byte[] getConstantPool(ReferenceType type) { if (Patches.JDK_BUG_ID_6822627) { try { return type.constantPool(); } catch (NullPointerException e) { // workaround for JDK bug 6822627 ReflectionUtil.resetField(type, "constantPoolInfoGotten"); return type.constantPool(); } } else { return type.constantPool(); } } private static void visit(Method method, byte[] bytecodes, MethodVisitor methodVisitor, boolean withLineNumbers) { ReferenceType type = method.declaringType(); try { byte[] constantPool = getConstantPool(type); try (ByteArrayBuilderOutputStream bos = new ByteArrayBuilderOutputStream(constantPool.length + 24); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeInt(0xCAFEBABE); // magic dos.writeInt(Opcodes.V1_8); // version dos.writeShort(type.constantPoolCount()); // constant_pool_count dos.write(constantPool); // constant_pool dos.writeShort(0); // access_flags; dos.writeShort(0); // this_class; dos.writeShort(0); // super_class; dos.writeShort(0); // interfaces_count; dos.writeShort(0); // fields_count; dos.writeShort(0); // methods_count; dos.writeShort(0); // attributes_count; ClassReader reader = new ClassReader(bos.getBuffer()); ClassWriter writer = new ClassWriter(reader, 0); String superName = null; String[] interfaces = null; if (type instanceof ClassType) { ClassType classType = (ClassType)type; ClassType superClass = classType.superclass(); superName = superClass != null ? superClass.name() : null; interfaces = classType.interfaces().stream().map(ReferenceType::name).toArray(String[]::new); } else if (type instanceof InterfaceType) { interfaces = ((InterfaceType)type).superinterfaces().stream().map(ReferenceType::name).toArray(String[]::new); } writer.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, type.name(), type.signature(), superName, interfaces); Attribute bootstrapMethods = createBootstrapMethods(reader, writer); if (bootstrapMethods != null) { writer.visitAttribute(bootstrapMethods); } MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, method.name(), method.signature(), method.signature(), null); mv.visitAttribute(createCode(writer, method, bytecodes, withLineNumbers)); new ClassReader(writer.toByteArray()).accept(new ClassVisitor(Opcodes.API_VERSION) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { assert name.equals(method.name()); return methodVisitor; } }, 0); } } catch (IOException ignored) { } } @NotNull private static Attribute createAttribute(String name, ThrowableConsumer<DataOutputStream, IOException> generator) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) { dos.writeInt(0xCAFEBABE); // magic dos.writeInt(Opcodes.V1_8); // version dos.writeShort(0); // constant_pool_count // we generate and put attribute right after the constant pool int attributeSize = dos.size(); generator.consume(dos); attributeSize = dos.size() - attributeSize; ClassReader cr = new ClassReader(bos.toByteArray()); return new Attribute(name) { @Override public Attribute read(ClassReader cr, int off, int len, char[] buf, int codeOff, Label[] labels) { return super.read(cr, off, len, buf, codeOff, labels); } }.read(cr, cr.header, attributeSize, null, 0, null); } } @Nullable private static Attribute createBootstrapMethods(ClassReader classReader, ClassWriter classWriter) throws IOException { Set<Short> indys = new HashSet<>(); // scan class pool for indy calls for (int i = 1; i < classReader.getItemCount(); i++) { int index = classReader.getItem(i); int tag = classReader.readByte(index - 1); switch (tag) { case 5: // ClassWriter.LONG case 6: // ClassWriter.DOUBLE ++i; break; case 18: // ClassWriter.INDY indys.add(classReader.readShort(index)); //short methodIndex = classReader.readShort(index); short nameTypeIndex = classReader.readShort(index + 2); } } if (!indys.isEmpty()) { int dummyRef = classWriter.newHandle(Opcodes.H_INVOKESTATIC, "DummyOwner", "DummyMethod", "", false); // dummy for now return createAttribute("BootstrapMethods", dos -> { dos.writeShort(indys.size()); for (Short indy : indys) { dos.writeShort(dummyRef); // bootstrap_method_ref dos.writeShort(0); // num_bootstrap_arguments //dos.writeShort(0); // bootstrap_arguments } }); } return null; } @NotNull private static Attribute createCode(ClassWriter cw, Method method, byte[] bytecodes, boolean withLineNumbers) throws IOException { return createAttribute("Code", dos -> { dos.writeShort(0); // max_stack dos.writeShort(0); // max_locals dos.writeInt(bytecodes.length); // code_length dos.write(bytecodes); // code dos.writeShort(0); // exception_table_length List<Location> locations = withLineNumbers ? DebuggerUtilsEx.allLineLocations(method) : Collections.emptyList(); if (!locations.isEmpty()) { dos.writeShort(1); // attributes_count dos.writeShort(cw.newUTF8("LineNumberTable")); dos.writeInt(2 * locations.size() + 2); dos.writeShort(locations.size()); for (Location l : locations) { dos.writeShort((short)l.codeIndex()); dos.writeShort(l.lineNumber()); } } else { dos.writeShort(0); // attributes_count } }); } private static final Type OBJECT_TYPE = Type.getObjectType("java/lang/Object"); public static Type getVarInstructionType(int opcode) { switch (opcode) { case Opcodes.LLOAD: case Opcodes.LSTORE: return Type.LONG_TYPE; case Opcodes.DLOAD: case Opcodes.DSTORE: return Type.DOUBLE_TYPE; case Opcodes.FLOAD: case Opcodes.FSTORE: return Type.FLOAT_TYPE; case Opcodes.ILOAD: case Opcodes.ISTORE: return Type.INT_TYPE; default: // case Opcodes.ALOAD: // case Opcodes.ASTORE: // case RET: return OBJECT_TYPE; } } @Nullable public static Method getLambdaMethod(ReferenceType clsType, VirtualMachineProxy vm) { Ref<Method> methodRef = Ref.create(); if (DebuggerUtilsEx.isLambdaClassName(clsType.name())) { List<Method> applicableMethods = ContainerUtil.filter(clsType.methods(), m -> m.isPublic() && !m.isBridge()); if (applicableMethods.size() == 1) { visit(applicableMethods.get(0), new MethodVisitor(Opcodes.API_VERSION) { @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { ReferenceType cls = ContainerUtil.getFirstItem(vm.classesByName(owner)); if (cls != null) { Method method = DebuggerUtils.findMethod(cls, name, desc); if (method != null) { methodRef.setIfNull(method); } } } }, false); } } return methodRef.get(); } @Nullable public static Method getBridgeTargetMethod(Method method, VirtualMachineProxy vm) { Ref<Method> methodRef = Ref.create(); if (method.isBridge()) { visit(method, new MethodVisitor(Opcodes.API_VERSION) { @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if ("java/lang/AbstractMethodError".equals(owner)) { return; } ReferenceType declaringType = method.declaringType(); ReferenceType cls; owner = owner.replace("/", "."); if (declaringType.name().equals(owner)) { cls = declaringType; } else { cls = ContainerUtil.getFirstItem(vm.classesByName(owner)); } if (cls != null) { Method method = DebuggerUtils.findMethod(cls, name, desc); if (method != null) { methodRef.setIfNull(method); } } } }, false); } return methodRef.get(); } private static class ByteArrayBuilderOutputStream extends ByteArrayOutputStream { public ByteArrayBuilderOutputStream(int size) { super(size); } byte[] getBuffer() { assert buf.length == count : "Buffer is not fully filled"; return buf; } } }
signed/intellij-community
java/debugger/impl/src/com/intellij/debugger/jdi/MethodBytecodeUtil.java
Java
apache-2.0
11,419
package org.ovirt.engine.core.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import org.ovirt.engine.core.common.businessentities.VmWatchdogType; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.osinfo.MapBackedPreferences; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.utils.Pair; import org.ovirt.engine.core.common.businessentities.DisplayType; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.common.businessentities.ArchitectureType; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; /** * This class is holding all Virtual OSs information. */ public enum OsRepositoryImpl implements OsRepository { INSTANCE; private static final Log log = LogFactory.getLog(OsRepositoryImpl.class); private static final String OS_ROOT_NODE = "/os/"; private static final String BACKWARD_COMPATIBILITY_ROOT_NODE = "/backwardCompatibility"; /** * the configuration tree holding all the os data. */ private MapBackedPreferences preferences; private Preferences emptyNode; /** * lookup table to get the os id from the uniquename and vise-versa os.rhel6.id.value = 8 means its id in the engine * db is 8 and the unique name is "rhel6" */ private Map<Integer, String> idToUnameLookup; private Map<String, Integer> backwardCompatibleNamesToIds; private static HashMap<ArchitectureType, Integer> defaultOsMap = new HashMap<ArchitectureType, Integer>(2); static { defaultOsMap.put(ArchitectureType.x86_64, DEFAULT_X86_OS); defaultOsMap.put(ArchitectureType.ppc64, DEFAULT_PPC_OS); } public void init(MapBackedPreferences preferences) { INSTANCE.preferences = preferences; emptyNode = preferences.node("emptyNode"); buildIdToUnameLookup(); buildBackCompatMapping(); validateTree(); if (log.isDebugEnabled()) { log.debugFormat("Osinfo Repository:\n {0}", toString()); } } private void validateTree() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); for (String uniqueName : Arrays.asList(uniqueNames)) { Preferences node = getKeyNode(uniqueName, "derivedFrom", null); String id = getKeyNode(uniqueName, "id", null).get("value", "0"); if (node != null) { String derivedFrom = node.get("value", null); if (derivedFrom != null && !idToUnameLookup.containsValue(derivedFrom)) { idToUnameLookup.remove(Integer.valueOf(id)); preferences.node("/os/" + uniqueName).removeNode(); log.warn("Illegal parent for os: " + uniqueName); } } } } catch (BackingStoreException e) { log.warn("Failed to validate Os Repository due to " + e); throw new RuntimeException("Failed to validate Os Repository due to " + e); } } private void buildIdToUnameLookup() { try { String[] uniqueNames = preferences.node("/os").childrenNames(); idToUnameLookup = new HashMap<Integer, String>(uniqueNames.length); for (String uniqueName : uniqueNames) { Preferences idNode = getKeyNode(uniqueName, "id", null); if (idNode != null) { idToUnameLookup.put(idNode.getInt("value", 0), uniqueName); } } } catch (BackingStoreException e) { throw new RuntimeException("Failed to initialize Os Repository due to " + e); } } private void buildBackCompatMapping() { try { String[] entries = preferences.node(BACKWARD_COMPATIBILITY_ROOT_NODE).keys(); backwardCompatibleNamesToIds = new HashMap<String, Integer>(entries.length); for (String oldOsName : entries) { backwardCompatibleNamesToIds.put(oldOsName, preferences.node(BACKWARD_COMPATIBILITY_ROOT_NODE).getInt(oldOsName, 0)); } } catch (BackingStoreException e) { throw new RuntimeException("Failed to initialize Os Repository Backward Compatibility mappings due to " + e); } } @Override public ArrayList<Integer> getOsIds() { return new ArrayList<Integer>(idToUnameLookup.keySet()); } @Override public HashMap<Integer, String> getUniqueOsNames() { // return a defensive copy to avoid modification of this map. return new HashMap<Integer, String>(idToUnameLookup); } @Override public HashMap<Integer, String> getOsNames() { HashMap<Integer, String> osNames = new HashMap<Integer, String>(); for (int osId : getOsIds()) { String name = getValueByVersion(idToUnameLookup.get(osId), "name", null); if (name != null) { osNames.put(osId, name); } } return osNames; } @Override public Map<Pair<Integer, Version>, Boolean> getNicHotplugSupportMap() { List<Version> versions = new ArrayList<Version>(Config.<HashSet<Version>> getValue(ConfigValues.SupportedClusterLevels)); Map<Pair<Integer, Version>, Boolean> hotplugSupportOsIdVersionMap = new HashMap<Pair<Integer, Version>, Boolean>(); for (Integer osId : getOsIds()) { for (Version version : versions) { hotplugSupportOsIdVersionMap.put( new Pair<Integer, Version>(osId, version), hasNicHotplugSupport(osId, version)); } } return hotplugSupportOsIdVersionMap; } @Override public Map<Pair<Integer, Version>, Set<String>> getDiskHotpluggableInterfacesMap() { Set<Version> versionsWithNull = new HashSet<Version>(Version.ALL); versionsWithNull.add(null); Map<Pair<Integer, Version>, Set<String>> diskHotpluggableInterfacesMap = new HashMap<Pair<Integer, Version>, Set<String>>(); for (Integer osId : getOsIds()) { for (Version version : versionsWithNull) { diskHotpluggableInterfacesMap.put( new Pair<Integer, Version>(osId, version), getDiskHotpluggableInterfaces(osId, version)); } } return diskHotpluggableInterfacesMap; } @Override public String getOsName(int osId) { return getOsNames().get(osId); } @Override public String getOsFamily(int osId) { return getValueByVersion(idToUnameLookup.get(osId), "family", null); } @Override public ArrayList<Integer> getLinuxOss() { ArrayList<Integer> oss = new ArrayList<Integer>(); for (int osId : getOsIds()) { if (getOsFamily(osId).equalsIgnoreCase("linux")) { oss.add(osId); } } return oss; } @Override public ArrayList<Integer> get64bitOss() { ArrayList<Integer> oss = new ArrayList<Integer>(); for (int osId : getOsIds()) { String bus = getValueByVersion(idToUnameLookup.get(osId), "bus", null); if ("64".equalsIgnoreCase(bus)) { oss.add(osId); } } return oss; } @Override public ArrayList<Integer> getWindowsOss() { ArrayList<Integer> oss = new ArrayList<Integer>(); for (int osId : getOsIds()) { if (isWindows(osId)) { oss.add(osId); } } return oss; } @Override public HashMap<Integer, ArchitectureType> getOsArchitectures() { HashMap<Integer, ArchitectureType> osArchitectures = new HashMap<Integer, ArchitectureType>(); for (int osId : getOsIds()) { String architecture = getValueByVersion(idToUnameLookup.get(osId), "cpuArchitecture", null); if (architecture != null) { osArchitectures.put(osId, ArchitectureType.valueOf(architecture)); } } return osArchitectures; } @Override public ArchitectureType getArchitectureFromOS(int osId) { String architecture = getValueByVersion(idToUnameLookup.get(osId), "cpuArchitecture", null); return ArchitectureType.valueOf(architecture); } @Override public boolean isWindows(int osId) { return getOsFamily(osId).equalsIgnoreCase("windows"); } @Override public ArrayList<String> getDiskInterfaces(int osId, Version version) { String devices = getValueByVersion(idToUnameLookup.get(osId), "devices.diskInterfaces", version); return trimElements(devices.split(",")); } @Override public ArrayList<String> getNetworkDevices(int osId, Version version) { String devices = getValueByVersion(idToUnameLookup.get(osId), "devices.network", version); return trimElements(devices.split(",")); } @Override public Set<String> getDiskHotpluggableInterfaces(int osId, Version version) { String devices = getValueByVersion(idToUnameLookup.get(osId), "devices.disk.hotpluggableInterfaces", version); return new HashSet<String>(trimElements(devices.split(","))); } @Override public ArrayList<String> getWatchDogModels(int osId, Version version) { String models = getValueByVersion(idToUnameLookup.get(osId), "devices.watchdog.models", version); return trimElements(models.split(",")); } @Override public Set<VmWatchdogType> getVmWatchdogTypes(int osId, Version version) { Set<VmWatchdogType> vmWatchdogTypes = new HashSet<VmWatchdogType>(); for (String watchDogModel : getWatchDogModels(osId, version)) { vmWatchdogTypes.add(VmWatchdogType.getByName(watchDogModel)); } return vmWatchdogTypes; } @Override public boolean isLinux(int osId) { return getOsFamily(osId).equalsIgnoreCase("linux"); } @Override public int getMinimumRam(int osId, Version version) { return getInt(getValueByVersion(idToUnameLookup.get(osId), "resources.minimum.ram", version), -1); } @Override public int getMaximumRam(int osId, Version version) { return getInt(getValueByVersion(idToUnameLookup.get(osId), "resources.maximum.ram", version), -1); } @Override public Map<Integer, Map<Version, List<DisplayType>>> getDisplayTypes() { Map<Integer, Map<Version, List<DisplayType>>> displayTypeMap = new HashMap<Integer, Map<Version, List<DisplayType>>>(); Set<Version> versionsWithNull = new HashSet<Version>(Version.ALL); versionsWithNull.add(null); for (Integer osId : getOsIds()) { displayTypeMap.put(osId, new HashMap<Version, List<DisplayType>>()); for (Version ver : versionsWithNull) { List<DisplayType> displayTypeList = getDisplayTypes(osId, ver); displayTypeMap.get(osId).put(ver, displayTypeList); } } return displayTypeMap; } public List<DisplayType> getDisplayTypes(int osId, Version version) { return new ArrayList<DisplayType>(parseDisplayProtocols(osId, version).keySet()); } private Map<DisplayType, VmDeviceType> parseDisplayProtocols(int osId, Version version) { Map<DisplayType, VmDeviceType> parseDisplayProtocols = new LinkedHashMap<DisplayType, VmDeviceType>(); String displayProtocolValue = getValueByVersion(idToUnameLookup.get(osId), "devices.display.protocols", version); for (String displayProtocol : displayProtocolValue.split(",")) { Pair<String, String> pairs = parseDisplayProtocol(displayProtocol); if (pairs != null) { parseDisplayProtocols.put(DisplayType.valueOf(pairs.getFirst()), VmDeviceType.getByName(pairs.getSecond())); } } return parseDisplayProtocols; } private Pair<String, String> parseDisplayProtocol(String displayProtocol) { Pair<String, String> pairs = null; String[] displayProtocolSplit = displayProtocol.split("/"); if (displayProtocolSplit.length == 2) { return new Pair<String, String>(displayProtocolSplit[0].trim(), displayProtocolSplit[1].trim()); } return pairs; } @Override public VmDeviceType getDisplayDevice(int osId, Version version, DisplayType displayType) { VmDeviceType vmDeviceType = parseDisplayProtocols(osId, version).get(displayType); return vmDeviceType == null ? displayType.getDefaultVmDeviceType() : vmDeviceType; } @Override public Map<Integer, Map<Version, Boolean>> getBalloonSupportMap() { Map<Integer, Map<Version, Boolean>> balloonSupportMap = new HashMap<Integer, Map<Version, Boolean>>(); Set<Version> versionsWithNull = new HashSet<Version>(Version.ALL); versionsWithNull.add(null); Set<Integer> osIds = new HashSet<Integer>(getOsIds()); for (Integer osId : osIds) { balloonSupportMap.put(osId, new HashMap<Version, Boolean>()); for (Version ver : versionsWithNull) { balloonSupportMap.get(osId).put(ver, isBalloonEnabled(osId, ver)); } } return balloonSupportMap; } @Override public boolean isBalloonEnabled(int osId, Version version) { return getBoolean(getValueByVersion(idToUnameLookup.get(osId), "devices.balloon.enabled", version), false); } @Override public boolean hasNicHotplugSupport(int osId, Version version) { return getBoolean(getValueByVersion(idToUnameLookup.get(osId), "devices.network.hotplugSupport", version), false); } @Override public String getSysprepPath(int osId, Version version) { return EngineLocalConfig.getInstance().expandString(getValueByVersion(idToUnameLookup.get(osId), "sysprepPath", version)); } @Override public String getProductKey(int osId, Version version) { return getValueByVersion(idToUnameLookup.get(osId), "productKey", version); } @Override public String getSoundDevice(int osId, Version version) { return getValueByVersion(idToUnameLookup.get(osId), "devices.audio", version); } @Override public int getMaxPciDevices(int osId, Version version) { return getInt(getValueByVersion(idToUnameLookup.get(osId), "devices.maxPciDevices", version), -1); } @Override public String getCdInterface(int osId, Version version) { return getValueByVersion(idToUnameLookup.get(osId), "devices.cdInterface", version); } @Override public boolean isTimezoneValueInteger(int osId, Version version) { return getBoolean(getValueByVersion(idToUnameLookup.get(osId), "isTimezoneTypeInteger", version), false); } @Override public boolean isHypervEnabled(int osId, Version version) { return getBoolean(getValueByVersion(idToUnameLookup.get(osId), "devices.hyperv.enabled", version), false); } @Override public int getOsIdByUniqueName(String uniqueOsName) { for (Map.Entry<Integer, String> entry : getUniqueOsNames().entrySet()) { if (entry.getValue().equals(uniqueOsName)) { return entry.getKey(); } } if (getBackwardCompatibleNamesToIds().containsKey(uniqueOsName)) { return getBackwardCompatibleNamesToIds().get(uniqueOsName); } return 0; } private boolean getBoolean(String value, boolean defaultValue) { return value == null ? defaultValue : Boolean.parseBoolean(value); } private int getInt(String value, int defaultValue) { try { return value == null ? defaultValue : Integer.parseInt(value); } catch (NumberFormatException ex) { return defaultValue; } } /** * get the value of the key specified by its version or the default version if not exist. see * {@link OsRepositoryImpl#getKeyNode} * * @param uniqueOsName * @param relativeKeyPath * @param version * @return */ private String getValueByVersion(String uniqueOsName, String relativeKeyPath, Version version) { Preferences keyNode = getKeyNode(uniqueOsName, relativeKeyPath, version); if (keyNode == emptyNode) { version = null; keyNode = getKeyNode(uniqueOsName, relativeKeyPath, null); } return keyNode.get(versionedValuePath(version), ""); } /** * * @param uniqueOsName * is the os.{String} section of the key path. \e.g "rhel6" is the unique os name of os.rhel6.description * key * @param version * the value version. e.g ver/os/rhel6/devices/sound/version.3.3 = ac97 * @return the node of the specified key for the given osId or its derived parent. Essentially this method will * recursively be called till no parent with the exact path is found. * */ private Preferences getKeyNode(String uniqueOsName, String relativeKeyPath, Version version) { if (uniqueOsName == null) { return emptyNode; } // first try direct OS node try { Preferences node = getNodeIfExist(uniqueOsName, relativeKeyPath); if (node != null && Arrays.asList(node.keys()).contains(versionedValuePath(version))) { return node; } else { // if not exist directly on the OS consult the one its derived from String derivedFromOs = preferences.node(OS_ROOT_NODE + uniqueOsName + "/derivedFrom").get("value", null); return derivedFromOs == null ? emptyNode : getKeyNode(derivedFromOs, relativeKeyPath, version); } } catch (BackingStoreException e) { // our preferences impl should use storage to back the data structure // throwing unchecked exception here to make sure this anomality is noticed throw new RuntimeException(e); } } /** * * @param osId unique name identifier. this is NOT the "id" attribute which is kept for backward compatibility. * @param key * @return the node which its path is /os/$osId/path/to/key otherwise null * @throws BackingStoreException */ private Preferences getNodeIfExist(String osId, String key) throws BackingStoreException { // make a full path name of some.key to os/$osId/some/key String pathName = OS_ROOT_NODE + osId + "/" + key.replaceAll("\\.", "/"); if (preferences.nodeExists(pathName)) { return preferences.node(pathName); } return null; } /** * helper method to retrieve a list of trimmed elements<br> * <p> * <code><b> foo, bar , baz </b></code> results <code><b>foo,bar,baz</b></code> * </p> * * @param elements * vararg of string elements. * @return new list where each value its whitespaces trimmed, and * is not added empty values. */ private ArrayList<String> trimElements(String... elements) { ArrayList<String> list = new ArrayList<String>(elements.length); for (String e : elements) { e = e.trim(); if (e.length() > 0) { list.add(e); } } return list; } /** * a key can have several values per version. a null version represents the default while other are specific one: * key.value = someval // the default value. the path returned is "value" key.value.3.1 = otherval // the 3.1 * version val. the path returned is "value.3.1" * * * @param version * @return the string representation of the value path. for key.value.3.1 = otherval "value.3.1" should be returned. */ private String versionedValuePath(Version version) { return version == null ? "value" : "value." + version.toString(); } @Override public boolean isSingleQxlDeviceEnabled(int osId) { return isLinux(osId); } public Map<String, Integer> getBackwardCompatibleNamesToIds() { return backwardCompatibleNamesToIds; } @Override public Map<ArchitectureType, Integer> getDefaultOSes() { return defaultOsMap; } @Override public String toString() { StringBuilder sb = new StringBuilder(); try { walkTree(sb, preferences); } catch (BackingStoreException e) { log.error(e.getStackTrace()); } return sb.toString(); } private void walkTree(StringBuilder sb, Preferences node) throws BackingStoreException { if (node.childrenNames().length == 0) { sb.append( node.absolutePath() .replaceFirst("/", "") .replace("/", ".")); for (String k : node.keys()) { sb.append("\n\t") .append(k) .append("=") .append(node.get(k, "")); } sb.append("\n"); } else { for (String nodePath : node.childrenNames()) { walkTree(sb, node.node(nodePath)); } } } }
halober/ovirt-engine
backend/manager/modules/utils/src/main/java/org/ovirt/engine/core/utils/OsRepositoryImpl.java
Java
apache-2.0
22,055
from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToonPythonUtil import addListsByValue class DistributedBattleFactoryAI(DistributedLevelBattleAI.DistributedLevelBattleAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedBattleFactoryAI') def __init__(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, roundCallback = None, finishCallback = None, maxSuits = 4): DistributedLevelBattleAI.DistributedLevelBattleAI.__init__(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, 'FactoryReward', roundCallback, finishCallback, maxSuits) self.battleCalc.setSkillCreditMultiplier(1) if self.bossBattle: self.level.d_setForemanConfronted(toonId) self.fsm.addState(State.State('FactoryReward', self.enterFactoryReward, self.exitFactoryReward, ['Resume'])) playMovieState = self.fsm.getStateNamed('PlayMovie') playMovieState.addTransition('FactoryReward') def getTaskZoneId(self): return self.level.factoryId def handleToonsWon(self, toons): for toon in toons: recovered, notRecovered = self.air.questManager.recoverItems(toon, self.suitsKilled, self.getTaskZoneId()) self.toonItems[toon.doId][0].extend(recovered) self.toonItems[toon.doId][1].extend(notRecovered) meritArray = self.air.promotionMgr.recoverMerits(toon, self.suitsKilled, self.getTaskZoneId(), getFactoryMeritMultiplier(self.getTaskZoneId())) if toon.doId in self.helpfulToons: self.toonMerits[toon.doId] = addListsByValue(self.toonMerits[toon.doId], meritArray) else: self.notify.debug('toon %d not helpful, skipping merits' % toon.doId) if self.bossBattle: self.toonParts[toon.doId] = self.air.cogSuitMgr.recoverPart(toon, self.level.factoryType, self.suitTrack, self.getTaskZoneId(), toons) self.notify.debug('toonParts = %s' % self.toonParts) def enterFactoryReward(self): self.joinableFsm.request('Unjoinable') self.runableFsm.request('Unrunable') self.resetResponses() self.assignRewards() self.bossDefeated = 1 self.level.setVictors(self.activeToons[:]) self.timer.startCallback(BUILDING_REWARD_TIMEOUT, self.serverRewardDone) return None def exitFactoryReward(self): return None def enterResume(self): DistributedLevelBattleAI.DistributedLevelBattleAI.enterResume(self) if self.bossBattle and self.bossDefeated: self.battleMgr.level.b_setDefeated()
silly-wacky-3-town-toon/SOURCE-COD
toontown/coghq/DistributedBattleFactoryAI.py
Python
apache-2.0
2,839
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.zlika.reproducible; import java.io.File; import java.io.IOException; import java.nio.file.Files; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link PropertiesFileStripper}. */ public class PropertiesFileStripperTest { /** * Tests stripping on a reference pom.properties file. * @throws IOException */ @Test public void testStripPom() throws IOException { final File out = File.createTempFile("pom", null); out.deleteOnExit(); new PropertiesFileStripper().strip(new File(this.getClass().getResource("pom.properties").getFile()), out); final byte[] expected = Files.readAllBytes(new File( this.getClass().getResource("pom-stripped.properties").getFile()).toPath()); final byte[] actual = Files.readAllBytes(out.toPath()); Assert.assertArrayEquals(expected, actual); out.delete(); } /** * Tests stripping on a reference git.properties file, with a list of properties to remove. * @throws IOException */ @Test public void testStripGitPropertiesFile() throws IOException { final File out = File.createTempFile("git", null); out.deleteOnExit(); new PropertiesFileStripper("git.build.host", "git.build.time", "git.build.user.email", "git.build.user.name") .strip(new File(this.getClass().getResource("git.properties").getFile()), out); final byte[] expected = Files.readAllBytes(new File( this.getClass().getResource("git-stripped.properties").getFile()).toPath()); final byte[] actual = Files.readAllBytes(out.toPath()); Assert.assertArrayEquals(expected, actual); out.delete(); } }
Zlika/reproducible-build-maven-plugin
src/test/java/io/github/zlika/reproducible/PropertiesFileStripperTest.java
Java
apache-2.0
2,398
// Karma configuration // Generated on Sat Sep 19 2015 21:44:51 GMT+0700 (SE Asia Standard Time) module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['browserify', 'jasmine'], browserify: { debug: true, transform: ['partialify', 'babelify'] }, // list of files / patterns to load in the browser files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'src/**/*', 'test/**/*Spec.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'src/**/*': ['browserify'], 'test/**/*Spec.js': ['browserify'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }) }
phucpnt/ng-timemachine
karma.conf.js
JavaScript
apache-2.0
1,881
package com.test.datastructures.implementations.strings; import org.junit.Before; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class RabinCarpSubstringSearchTest { private RabinCarpSubstringSearch patient; private static final String NULL_STRING = null; private static final String EMPTY_STRING = ""; private static final String STUB_STRING_LONG = "Just a stub string"; private static final String STUB_STRING_SHORT = "Hodor"; private static final String TEST0_INITIAL = "Hello, World!"; private static final String TEST0_PATTERN = "World"; private static final String TEST1_INITIAL = "Hello"; private static final String TEST1_PATTERN = "Hello"; private static final String TEST2_INITIAL = "Hello"; private static final String TEST2_PATTERN = "hello"; @Before public void before() { patient = new RabinCarpSubstringSearch(); } @Test public void searchSubstring_Test0Data_IndexIsNotMinusOne() { int index = patient.findFirstSubstringIndex(TEST0_INITIAL, TEST0_PATTERN); assertThat(index, not(-1)); } @Test public void searchSubstring_Test0Data_IndexSameAsForJavaApi() { int index = patient.findFirstSubstringIndex(TEST0_INITIAL, TEST0_PATTERN); assertThat(index, equalTo(TEST0_INITIAL.indexOf(TEST0_PATTERN))); } @Test public void searchSubstring_Test1Data_IndexIsNotMinusOne() { int index = patient.findFirstSubstringIndex(TEST1_INITIAL, TEST1_PATTERN); assertThat(index, not(-1)); } @Test public void searchSubstring_Test1Data_IndexSameAsForJavaApi() { int index = patient.findFirstSubstringIndex(TEST1_INITIAL, TEST1_PATTERN); assertThat(index, equalTo(TEST1_INITIAL.indexOf(TEST1_PATTERN))); } @Test public void searchSubstring_Test2Data_IndexIsMinusOne() { int index = patient.findFirstSubstringIndex(TEST2_INITIAL, TEST2_PATTERN); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_Test2Data_IndexSameAsForJavaApi() { int index = patient.findFirstSubstringIndex(TEST2_INITIAL, TEST2_PATTERN); assertThat(index, equalTo(TEST2_INITIAL.indexOf(TEST2_PATTERN))); } @Test public void searchSubstring_BothInputsAreNull_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(NULL_STRING, NULL_STRING); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_InitialIsNull_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(NULL_STRING, STUB_STRING_LONG); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_PatternIsNull_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(STUB_STRING_LONG, NULL_STRING); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_InitialIsEmpty_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(EMPTY_STRING, STUB_STRING_LONG); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_PatternIsEmpty_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(STUB_STRING_LONG, EMPTY_STRING); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_InitialIsNullPatternIsEmpty_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(NULL_STRING, EMPTY_STRING); assertThat(index, equalTo(-1)); } @Test public void searchSubstring_InitialIsShorterThenPattern_ReturnMinusOne() { int index = patient.findFirstSubstringIndex(STUB_STRING_SHORT, STUB_STRING_LONG); assertThat(index, equalTo(-1)); } }
081krieger/data-structures
src/test/java/com/test/datastructures/implementations/strings/RabinCarpSubstringSearchTest.java
Java
apache-2.0
3,770
package osm_2019 import ( "fmt" "strings" ) type Table struct { Headers []*TableHeader Rows []*TableRow } type TableHeader struct { Text string width int } type TableRow struct { Cells []*TableCell } type TableCell struct { Text string } func (t *Table) Header(s ...string) *Table { for _, h := range s { t.Headers = append(t.Headers, &TableHeader{Text: h}) } return t } func (t *Table) AddRow() *TableRow { r := &TableRow{} t.Rows = append(t.Rows, r) return r } func (r *TableRow) Add(s ...string) *TableRow { for _, v := range s { r.Cells = append(r.Cells, &TableCell{Text: v}) } return r } func (c *TableCell) toString(w int) string { if c == nil || c.Text == "" { return strings.Repeat(" ", w) } return cellToString(c.Text, w) } func cellToString(s string, w int) string { if s == "" { return strings.Repeat(" ", w) } if len(s) > w { return s[:w] } return s + strings.Repeat(" ", w-len(s)) } func rowToString(s []string) string { return "| " + strings.Join(s, " | ") + " |" } func (t *Table) String() string { // Calculate the cell widths for _, h := range t.Headers { h.width = len(h.Text) } for _, r := range t.Rows { for i, c := range r.Cells { var h *TableHeader if i >= len(t.Headers) { t.Header(fmt.Sprintf("Column %d", i)) h = t.Headers[i] h.width = len(h.Text) } else { h = t.Headers[i] } if c != nil { l := len(c.Text) if l > h.width { h.width = l } } } } var l []string var hs []string // line separator for _, h := range t.Headers { l = append(l, strings.Repeat("-", h.width)) hs = append(hs, cellToString(h.Text, h.width)) } sep := "+-" + strings.Join(l, "-+-") + "-+" var out []string out = append(out, sep, rowToString(hs), sep) for _, r := range t.Rows { l = nil for i, c := range r.Cells { l = append(l, c.toString(t.Headers[i].width)) } out = append(out, rowToString(l), sep) } return strings.Join(out, "\n") }
peter-mount/map.lu
osm-2019/table.go
GO
apache-2.0
1,980
name 'cloudrim' maintainer 'YOUR_COMPANY_NAME' maintainer_email 'YOUR_EMAIL' license 'All rights reserved' description 'Installs/Configures cloudrim' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0'
krogebry/cloudrim-chef
metadata.rb
Ruby
apache-2.0
280
/** * */ /** * @author kevinbayes * */ package me.bayes.vertx.vest.handler;
kevinbayes/vest
src/main/java/me/bayes/vertx/vest/handler/package-info.java
Java
apache-2.0
81
package com.github.ninerules.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface IgnoreRules{ }
tamada/9rules
src/main/java/com/github/ninerules/annotation/IgnoreRules.java
Java
apache-2.0
179
#include "liba.h" #include <math.h> #ifndef REQUIRED_DEFINE // '-DREQUIRED_DEFINE' is set via the copts attribute of the make rule. #error "REQUIRED_DEFINE is not defined" #endif std::string hello_liba(void) { return "Hello from LIBA!"; } double hello_math(double a) { // On Unix, this call requires linking to libm.so. The Bazel toolchain adds // the required `-lm` linkopt automatically and rules_foreign_cc forwards // this option to make invocation via the CXXFLAGS variable. return acos(a); }
bazelbuild/rules_foreign_cc
examples/make_simple/code/liba.cpp
C++
apache-2.0
507
/** * Copyright 2011-2015 Timothy James Hruska (tjhruska@yahoo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tjhruska.mc.database.restrictions; import java.util.Collection; import java.util.Map; public class Restrictions { public static Restriction allEq(Map<String, Object> propertyNameValues) { return PropertyRestriction.allEq(propertyNameValues); } public static Restriction and(Restriction lhs, Restriction rhs) { return EvalRestriction.and(lhs, rhs); } public static Restriction between(String propertyName, Object lo, Object hi) { return PropertyRestriction.between(propertyName, lo, hi); } public static Restriction eq(String propertyName, Object value) { return PropertyRestriction.eq(propertyName, value); } public static Restriction ge(String propertyName, Object value) { return PropertyRestriction.ge(propertyName, value); } public static Restriction gt(String propertyName, Object value) { return PropertyRestriction.gt(propertyName, value); } public static Restriction ilike(String propertyName, Object value) { return PropertyRestriction.ilike(propertyName, value); } public static Restriction in(String propertyName, Collection<Object> values) { return PropertyRestriction.inCollection(propertyName, values); } public static Restriction in(String propertyName, Object[] values) { return PropertyRestriction.inArray(propertyName, values); } public static Restriction isNotNull(String propertyName) { return PropertyRestriction.isNotNull(propertyName); } public static Restriction isNull(String propertyName) { return PropertyRestriction.isNull(propertyName); } public static Restriction le(String propertyName, Object value) { return PropertyRestriction.le(propertyName, value); } public static Restriction like(String propertyName, Object value) { return PropertyRestriction.like(propertyName, value); } public static Restriction lt(String propertyName, Object value) { return PropertyRestriction.lt(propertyName, value); } public static Restriction ne(String propertyName, Object value) { return PropertyRestriction.ne(propertyName, value); } public static Restriction not(Restriction expression) { return EvalRestriction.not(expression); } public static Restriction or(Restriction lhs, Restriction rhs) { return EvalRestriction.or(lhs, rhs); } }
tjhruska/mc-framework
src/main/groovy/com/tjhruska/mc/database/restrictions/Restrictions.java
Java
apache-2.0
2,959
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { function back() { "prepaid" == Alloy.Globals.userPlan ? DRAWER.navigation("prepaidStatement", 1) : DRAWER.navigation("postpaidStatement", 1); } require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "iddVoice"; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; var __defers = {}; $.__views.iddVoice = Ti.UI.createView({ backgroundColor: "white", layout: "vertical", fullscreen: "true", id: "iddVoice" }); $.__views.iddVoice && $.addTopLevelView($.__views.iddVoice); $.__views.__alloyId1002 = Alloy.createController("_header", { id: "__alloyId1002", __parentSymbol: $.__views.iddVoice }); $.__views.__alloyId1002.setParent($.__views.iddVoice); $.__views.__alloyId1003 = Ti.UI.createView({ layout: "composite", height: "50", backgroundColor: "#E91D2F", id: "__alloyId1003" }); $.__views.iddVoice.add($.__views.__alloyId1003); $.__views.__alloyId1004 = Ti.UI.createLabel({ text: "Bill Statement", backgroundColor: "transparent", color: "white", left: "20", id: "__alloyId1004" }); $.__views.__alloyId1003.add($.__views.__alloyId1004); $.__views.__alloyId1005 = Ti.UI.createImageView({ backgroundColor: "transparent", width: "30", height: "30", right: "10", image: "/images/close_icon.png", id: "__alloyId1005" }); $.__views.__alloyId1003.add($.__views.__alloyId1005); back ? $.__views.__alloyId1005.addEventListener("click", back) : __defers["$.__views.__alloyId1005!click!back"] = true; $.__views.__alloyId1006 = Ti.UI.createView({ layout: "composite", height: "40", backgroundColor: "#F2F2F2", id: "__alloyId1006" }); $.__views.iddVoice.add($.__views.__alloyId1006); $.__views.__alloyId1007 = Ti.UI.createLabel({ text: "IDD Voice Calls", textAlign: "center", color: "black", left: "10", id: "__alloyId1007" }); $.__views.__alloyId1006.add($.__views.__alloyId1007); var __alloyId1008 = []; $.__views.__alloyId1009 = Ti.UI.createTableViewSection({ id: "__alloyId1009" }); __alloyId1008.push($.__views.__alloyId1009); $.__views.__alloyId1010 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1010" }); $.__views.__alloyId1009.add($.__views.__alloyId1010); $.__views.__alloyId1011 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1011" }); $.__views.__alloyId1010.add($.__views.__alloyId1011); $.__views.__alloyId1012 = Ti.UI.createLabel({ text: "01/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1012" }); $.__views.__alloyId1011.add($.__views.__alloyId1012); $.__views.__alloyId1013 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1013" }); $.__views.__alloyId1010.add($.__views.__alloyId1013); $.__views.__alloyId1014 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1014" }); $.__views.__alloyId1013.add($.__views.__alloyId1014); $.__views.__alloyId1015 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1015" }); $.__views.__alloyId1010.add($.__views.__alloyId1015); $.__views.__alloyId1016 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1016" }); $.__views.__alloyId1015.add($.__views.__alloyId1016); $.__views.__alloyId1017 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1017" }); $.__views.__alloyId1009.add($.__views.__alloyId1017); $.__views.__alloyId1018 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1018" }); $.__views.__alloyId1017.add($.__views.__alloyId1018); $.__views.__alloyId1019 = Ti.UI.createLabel({ text: "02/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1019" }); $.__views.__alloyId1018.add($.__views.__alloyId1019); $.__views.__alloyId1020 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1020" }); $.__views.__alloyId1017.add($.__views.__alloyId1020); $.__views.__alloyId1021 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1021" }); $.__views.__alloyId1020.add($.__views.__alloyId1021); $.__views.__alloyId1022 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1022" }); $.__views.__alloyId1017.add($.__views.__alloyId1022); $.__views.__alloyId1023 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1023" }); $.__views.__alloyId1022.add($.__views.__alloyId1023); $.__views.__alloyId1024 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1024" }); $.__views.__alloyId1009.add($.__views.__alloyId1024); $.__views.__alloyId1025 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1025" }); $.__views.__alloyId1024.add($.__views.__alloyId1025); $.__views.__alloyId1026 = Ti.UI.createLabel({ text: "03/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1026" }); $.__views.__alloyId1025.add($.__views.__alloyId1026); $.__views.__alloyId1027 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1027" }); $.__views.__alloyId1024.add($.__views.__alloyId1027); $.__views.__alloyId1028 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1028" }); $.__views.__alloyId1027.add($.__views.__alloyId1028); $.__views.__alloyId1029 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1029" }); $.__views.__alloyId1024.add($.__views.__alloyId1029); $.__views.__alloyId1030 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1030" }); $.__views.__alloyId1029.add($.__views.__alloyId1030); $.__views.__alloyId1031 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1031" }); $.__views.__alloyId1009.add($.__views.__alloyId1031); $.__views.__alloyId1032 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1032" }); $.__views.__alloyId1031.add($.__views.__alloyId1032); $.__views.__alloyId1033 = Ti.UI.createLabel({ text: "04/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1033" }); $.__views.__alloyId1032.add($.__views.__alloyId1033); $.__views.__alloyId1034 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1034" }); $.__views.__alloyId1031.add($.__views.__alloyId1034); $.__views.__alloyId1035 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1035" }); $.__views.__alloyId1034.add($.__views.__alloyId1035); $.__views.__alloyId1036 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1036" }); $.__views.__alloyId1031.add($.__views.__alloyId1036); $.__views.__alloyId1037 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1037" }); $.__views.__alloyId1036.add($.__views.__alloyId1037); $.__views.__alloyId1038 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1038" }); $.__views.__alloyId1009.add($.__views.__alloyId1038); $.__views.__alloyId1039 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1039" }); $.__views.__alloyId1038.add($.__views.__alloyId1039); $.__views.__alloyId1040 = Ti.UI.createLabel({ text: "05/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1040" }); $.__views.__alloyId1039.add($.__views.__alloyId1040); $.__views.__alloyId1041 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1041" }); $.__views.__alloyId1038.add($.__views.__alloyId1041); $.__views.__alloyId1042 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1042" }); $.__views.__alloyId1041.add($.__views.__alloyId1042); $.__views.__alloyId1043 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1043" }); $.__views.__alloyId1038.add($.__views.__alloyId1043); $.__views.__alloyId1044 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1044" }); $.__views.__alloyId1043.add($.__views.__alloyId1044); $.__views.__alloyId1045 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1045" }); $.__views.__alloyId1009.add($.__views.__alloyId1045); $.__views.__alloyId1046 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1046" }); $.__views.__alloyId1045.add($.__views.__alloyId1046); $.__views.__alloyId1047 = Ti.UI.createLabel({ text: "06/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1047" }); $.__views.__alloyId1046.add($.__views.__alloyId1047); $.__views.__alloyId1048 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1048" }); $.__views.__alloyId1045.add($.__views.__alloyId1048); $.__views.__alloyId1049 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1049" }); $.__views.__alloyId1048.add($.__views.__alloyId1049); $.__views.__alloyId1050 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1050" }); $.__views.__alloyId1045.add($.__views.__alloyId1050); $.__views.__alloyId1051 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1051" }); $.__views.__alloyId1050.add($.__views.__alloyId1051); $.__views.__alloyId1052 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1052" }); $.__views.__alloyId1009.add($.__views.__alloyId1052); $.__views.__alloyId1053 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1053" }); $.__views.__alloyId1052.add($.__views.__alloyId1053); $.__views.__alloyId1054 = Ti.UI.createLabel({ text: "07/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1054" }); $.__views.__alloyId1053.add($.__views.__alloyId1054); $.__views.__alloyId1055 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1055" }); $.__views.__alloyId1052.add($.__views.__alloyId1055); $.__views.__alloyId1056 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1056" }); $.__views.__alloyId1055.add($.__views.__alloyId1056); $.__views.__alloyId1057 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1057" }); $.__views.__alloyId1052.add($.__views.__alloyId1057); $.__views.__alloyId1058 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1058" }); $.__views.__alloyId1057.add($.__views.__alloyId1058); $.__views.__alloyId1059 = Ti.UI.createTableViewRow({ height: "80", width: "100%", layout: "horizontal", separatorColor: "#000", id: "__alloyId1059" }); $.__views.__alloyId1009.add($.__views.__alloyId1059); $.__views.__alloyId1060 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1060" }); $.__views.__alloyId1059.add($.__views.__alloyId1060); $.__views.__alloyId1061 = Ti.UI.createLabel({ text: "08/03/2015 12:05:07", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1061" }); $.__views.__alloyId1060.add($.__views.__alloyId1061); $.__views.__alloyId1062 = Ti.UI.createView({ width: "33%", height: "100", id: "__alloyId1062" }); $.__views.__alloyId1059.add($.__views.__alloyId1062); $.__views.__alloyId1063 = Ti.UI.createLabel({ text: "On Net 6017000000", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1063" }); $.__views.__alloyId1062.add($.__views.__alloyId1063); $.__views.__alloyId1064 = Ti.UI.createView({ width: "33%", height: "100%", id: "__alloyId1064" }); $.__views.__alloyId1059.add($.__views.__alloyId1064); $.__views.__alloyId1065 = Ti.UI.createLabel({ text: "9 (sec) RM0.05", backgroundColor: "transparent", color: "black", textAlign: "left", left: "10", id: "__alloyId1065" }); $.__views.__alloyId1064.add($.__views.__alloyId1065); $.__views.table = Ti.UI.createTableView({ data: __alloyId1008, id: "table", scrollable: "true" }); $.__views.iddVoice.add($.__views.table); exports.destroy = function() {}; _.extend($, $.__views); __defers["$.__views.__alloyId1005!click!back"] && $.__views.__alloyId1005.addEventListener("click", back); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
hardikamal/xox
Resources/iphone/alloy/controllers/iddVoice.js
JavaScript
apache-2.0
16,804
/* * Copyright (C) 2015 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package OptimizationTests.ShortMethodsInliningNonVirtualInvokes.InvokeSuperRangeAObjectThrowBoundSet_001; // The test checks that stack after ArrayIndexOutOfBoundsException occurs is correct despite inlining class Test extends SuperTest { Test(int iterations) { super(iterations); } public Foo getThingies(Foo[] arr, int i, Foo f1, Foo f2, Foo f3, Foo f4, Foo f5, Foo f6) { return super.getThingies(arr, i, f1, f2, f3, f4, f5, f6); } public void setThingies(Foo[] arr, Foo newThingy, int i, Foo f1, Foo f2, Foo f3, Foo f4, Foo f5, Foo f6) { super.setThingies(arr, newThingy, i, f1, f2, f3, f4, f5, f6); } }
android-art-intel/marshmallow
art-extension/opttests/src/OptimizationTests/ShortMethodsInliningNonVirtualInvokes/InvokeSuperRangeAObjectThrowBoundSet_001/Test.java
Java
apache-2.0
1,266
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.wan; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.UnknownHostException; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.internal.cache.CacheServerImpl; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.net.SocketCreator; import org.apache.geode.test.junit.categories.UnitTest; @Category(UnitTest.class) public class GatewayReceiverImplJUnitTest { @Test public void getHostOnUnstartedGatewayShouldReturnLocalhost() throws UnknownHostException { InternalCache cache = mock(InternalCache.class); GatewayReceiverImpl gateway = new GatewayReceiverImpl(cache, 2000, 2001, 5, 100, null, null, null, true); assertEquals(SocketCreator.getLocalHost().getHostName(), gateway.getHost()); } @Test public void getHostOnRunningGatewayShouldReturnCacheServerAddress() throws IOException { InternalCache cache = mock(InternalCache.class); CacheServerImpl server = mock(CacheServerImpl.class); InternalDistributedSystem system = mock(InternalDistributedSystem.class); when(cache.getInternalDistributedSystem()).thenReturn(system); when(server.getExternalAddress()).thenReturn("hello"); when(cache.addCacheServer(eq(true))).thenReturn(server); GatewayReceiverImpl gateway = new GatewayReceiverImpl(cache, 2000, 2001, 5, 100, null, null, null, true); gateway.start(); assertEquals("hello", gateway.getHost()); } }
charliemblack/geode
geode-wan/src/test/java/org/apache/geode/internal/cache/wan/GatewayReceiverImplJUnitTest.java
Java
apache-2.0
2,527
#!/usr/bin/python from light import Light light = Light() print light.getstate()
bettse/hue
dump.py
Python
apache-2.0
82
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.postgresql.edit; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.postgresql.model.PostgreDataSource; import org.jkiss.dbeaver.ext.postgresql.model.PostgreDatabase; import org.jkiss.dbeaver.ext.postgresql.model.PostgreEventTrigger; import org.jkiss.dbeaver.model.DBConstants; import org.jkiss.dbeaver.model.DBPDataSource; import org.jkiss.dbeaver.model.DBUtils; import org.jkiss.dbeaver.model.edit.DBECommandContext; import org.jkiss.dbeaver.model.edit.DBEObjectRenamer; import org.jkiss.dbeaver.model.edit.DBEPersistAction; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.edit.SQLDatabasePersistAction; import org.jkiss.dbeaver.model.impl.sql.edit.struct.SQLTriggerManager; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.sql.SQLUtils; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.cache.DBSObjectCache; import org.jkiss.utils.CommonUtils; import java.util.List; import java.util.Map; /** * PostgreEventTriggerManager */ public class PostgreEventTriggerManager extends SQLTriggerManager<PostgreEventTrigger, PostgreDatabase> implements DBEObjectRenamer<PostgreEventTrigger> { @Override public boolean canCreateObject(Object container) { return true; } @Override public long getMakerOptions(DBPDataSource dataSource) { return FEATURE_EDITOR_ON_CREATE; } @Override public DBSObjectCache<? extends DBSObject, PostgreEventTrigger> getObjectsCache(PostgreEventTrigger object) { return object.getDatabase().getEventTriggersCache(); } @Override protected PostgreEventTrigger createDatabaseObject(DBRProgressMonitor monitor, DBECommandContext context, Object container, Object copyFrom, Map<String, Object> options) { return new PostgreEventTrigger((PostgreDatabase) container, "new_event_trigger"); } @Override protected void addObjectModifyActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectChangeCommand command, Map<String, Object> options) { if (command.getProperties().size() > 1 || command.getProperty(DBConstants.PROP_ID_DESCRIPTION) == null) { createOrReplaceTriggerQuery(monitor, executionContext, actions, command.getObject(), false); } } @Override protected void addObjectExtraActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, NestedObjectCommand<PostgreEventTrigger, PropertyHandler> command, Map<String, Object> options) { if (command.hasProperty(DBConstants.PROP_ID_DESCRIPTION)) { PostgreEventTrigger trigger = command.getObject(); actions.add(new SQLDatabasePersistAction( "Comment event trigger", "COMMENT ON EVENT TRIGGER " + DBUtils.getQuotedIdentifier(trigger) + " IS " + SQLUtils.quoteString(trigger, CommonUtils.notEmpty(trigger.getDescription())))); } } @Override protected void createOrReplaceTriggerQuery(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, PostgreEventTrigger trigger, boolean create) { if (trigger.isPersisted()) { actions.add(new SQLDatabasePersistAction( "Drop event trigger", "DROP EVENT TRIGGER IF EXISTS " + DBUtils.getQuotedIdentifier(trigger) )); } actions.add(new SQLDatabasePersistAction("Create trigger", trigger.getBody())); } @Override protected void addObjectDeleteActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectDeleteCommand command, Map<String, Object> options) { actions.add(new SQLDatabasePersistAction( "Drop event trigger", "DROP EVENT TRIGGER " + DBUtils.getQuotedIdentifier(command.getObject()) )); } @Override public void renameObject(@NotNull DBECommandContext commandContext, @NotNull PostgreEventTrigger object, @NotNull Map<String, Object> options, @NotNull String newName) throws DBException { processObjectRename(commandContext, object, options, newName); } @Override protected void addObjectRenameActions(DBRProgressMonitor monitor, DBCExecutionContext executionContext, List<DBEPersistAction> actions, ObjectRenameCommand command, Map<String, Object> options) { PostgreDataSource dataSource = command.getObject().getDataSource(); actions.add(new SQLDatabasePersistAction( "Rename event trigger", "ALTER EVENT TRIGGER " + DBUtils.getQuotedIdentifier(dataSource, command.getOldName()) + " RENAME TO " + DBUtils.getQuotedIdentifier(dataSource, command.getNewName()) )); } }
dbeaver/dbeaver
plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/edit/PostgreEventTriggerManager.java
Java
apache-2.0
5,594
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs // 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: 2012.10.05 at 01:53:24 오후 KST // package com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for resource-descriptionType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="resource-descriptionType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="res-ref-name" type="{http://java.sun.com/xml/ns/j2ee}jndi-nameType"/> * &lt;group ref="{http://www.bea.com/ns/weblogic/90}resource-lookup"/> * &lt;/sequence> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "resource-descriptionType", propOrder = { "resRefName", "jndiName", "resourceLink" }) public class ResourceDescriptionType { @XmlElement(name = "res-ref-name", namespace = "http://www.bea.com/ns/weblogic/90", required = true) protected JndiNameType resRefName; @XmlElement(name = "jndi-name", namespace = "http://www.bea.com/ns/weblogic/90") protected com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String jndiName; @XmlElement(name = "resource-link", namespace = "http://www.bea.com/ns/weblogic/90") protected com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String resourceLink; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID protected java.lang.String id; /** * Gets the value of the resRefName property. * * @return * possible object is * {@link JndiNameType } * */ public JndiNameType getResRefName() { return resRefName; } /** * Sets the value of the resRefName property. * * @param value * allowed object is * {@link JndiNameType } * */ public void setResRefName(JndiNameType value) { this.resRefName = value; } /** * Gets the value of the jndiName property. * * @return * possible object is * {@link com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String } * */ public com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String getJndiName() { return jndiName; } /** * Sets the value of the jndiName property. * * @param value * allowed object is * {@link com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String } * */ public void setJndiName(com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String value) { this.jndiName = value; } /** * Gets the value of the resourceLink property. * * @return * possible object is * {@link com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String } * */ public com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String getResourceLink() { return resourceLink; } /** * Sets the value of the resourceLink property. * * @param value * allowed object is * {@link com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String } * */ public void setResourceLink(com.athena.chameleon.engine.entity.xml.application.weblogic.v9_0.String value) { this.resourceLink = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } }
OpenSourceConsulting/athena-chameleon
src/main/java/com/athena/chameleon/engine/entity/xml/application/weblogic/v9_0/ResourceDescriptionType.java
Java
apache-2.0
4,816
package com.google.api.ads.dfp.jaxws.v201311; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Creates new {@link CustomField} objects. * * The following fields are required: * <ul> * <li>{@link CustomField#name}</li> * <li>{@link CustomField#entityType}</li> * <li>{@link CustomField#dataType}</li> * <li>{@link CustomField#visibility}</li> * </ul> * * @param customFields the custom fields to create * @return the created custom fields with their IDs filled in * * * <p>Java class for createCustomFields element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="createCustomFields"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="customFields" type="{https://www.google.com/apis/ads/publisher/v201311}CustomField" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "customFields" }) @XmlRootElement(name = "createCustomFields") public class CustomFieldServiceInterfacecreateCustomFields { protected List<CustomField> customFields; /** * Gets the value of the customFields property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the customFields property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCustomFields().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CustomField } * * */ public List<CustomField> getCustomFields() { if (customFields == null) { customFields = new ArrayList<CustomField>(); } return this.customFields; } }
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201311/CustomFieldServiceInterfacecreateCustomFields.java
Java
apache-2.0
2,594
/* * Copyright 2005-2007 The Kuali Foundation * * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kew.rule.web; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.kuali.rice.core.api.exception.RiceRuntimeException; import org.kuali.rice.kew.api.action.ActionRequestPolicy; import org.kuali.rice.kew.doctype.bo.DocumentType; import org.kuali.rice.kew.rule.GroupRuleResponsibility; import org.kuali.rice.kew.rule.PersonRuleResponsibility; import org.kuali.rice.kew.rule.RoleRuleResponsibility; import org.kuali.rice.kew.rule.RuleBaseValues; import org.kuali.rice.kew.rule.RuleDelegationBo; import org.kuali.rice.kew.rule.RuleExtension; import org.kuali.rice.kew.rule.RuleExtensionValue; import org.kuali.rice.kew.rule.RuleResponsibilityBo; import org.kuali.rice.kew.rule.WorkflowAttribute; import org.kuali.rice.kew.rule.bo.RuleAttribute; import org.kuali.rice.kew.rule.bo.RuleTemplateAttributeBo; import org.kuali.rice.kew.rule.bo.RuleTemplateBo; import org.kuali.rice.kew.rule.service.RuleServiceInternal; import org.kuali.rice.kew.rule.xmlrouting.GenericXMLRuleAttribute; import org.kuali.rice.kew.service.KEWServiceLocator; import org.kuali.rice.kew.util.KEWConstants; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kns.web.ui.Field; import org.kuali.rice.kns.web.ui.Row; import org.kuali.rice.kns.web.ui.Section; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Some utilities which are utilized by the {@link RuleAction}. * * @author Kuali Rice Team (rice.collab@kuali.org) */ public final class WebRuleUtils { public static final String RULE_TEMPLATE_ID_PARAM = "ruleCreationValues.ruleTemplateId"; public static final String RULE_TEMPLATE_NAME_PARAM = "ruleCreationValues.ruleTemplateName"; public static final String DOCUMENT_TYPE_NAME_PARAM = "ruleCreationValues.docTypeName"; public static final String RESPONSIBILITY_ID_PARAM = "ruleCreationValues.responsibilityId"; private static final String ID_SEPARATOR = ":"; private static final String RULE_ATTRIBUTES_SECTION_ID = "RuleAttributes"; private static final String RULE_ATTRIBUTES_SECTION_TITLE = "Rule Attributes"; private static final String ROLES_MAINTENANCE_SECTION_ID = "RolesMaintenance"; private WebRuleUtils() { throw new UnsupportedOperationException("do not call"); } /** * Copies the existing rule onto the current document. This is used within the web-based rule GUI to make a * copy of a rule on the existing document. Essentially, this method makes a copy of the rule and all * delegates but preserves the document ID of the original rule. */ public static WebRuleBaseValues copyRuleOntoExistingDocument(WebRuleBaseValues rule) throws Exception { WebRuleBaseValues ruleCopy = new WebRuleBaseValues(); PropertyUtils.copyProperties(ruleCopy, rule); ruleCopy.setPreviousVersionId(null); ruleCopy.setCurrentInd(null); ruleCopy.setVersionNbr(null); List responsibilities = new ArrayList(); for (Iterator iter = ruleCopy.getRuleResponsibilities().iterator(); iter.hasNext();) { WebRuleResponsibility responsibility = (WebRuleResponsibility) iter.next(); WebRuleResponsibility responsibilityCopy = new WebRuleResponsibility(); PropertyUtils.copyProperties(responsibilityCopy, responsibility); responsibilityCopy.setResponsibilityId(null); responsibilityCopy.setId(null); List delegations = new ArrayList(); for (Iterator iterator = responsibilityCopy.getDelegationRules().iterator(); iterator.hasNext();) { RuleDelegationBo delegation = (RuleDelegationBo) iterator.next(); RuleDelegationBo delegationCopy = new RuleDelegationBo(); PropertyUtils.copyProperties(delegationCopy, delegation); delegationCopy.setDelegateRuleId(null); delegationCopy.setVersionNumber(null); delegationCopy.setRuleDelegationId(null); delegationCopy.setResponsibilityId(null); WebRuleBaseValues delegationRule = ((WebRuleBaseValues) delegation.getDelegationRule()); WebRuleBaseValues ruleDelegateCopy = new WebRuleBaseValues(); PropertyUtils.copyProperties(ruleDelegateCopy, delegationRule); ruleDelegateCopy.setPreviousVersionId(null); ruleDelegateCopy.setCurrentInd(null); ruleDelegateCopy.setVersionNbr(null); List delegateResps = new ArrayList(); for (Iterator iterator1 = ruleDelegateCopy.getRuleResponsibilities().iterator(); iterator1.hasNext();) { WebRuleResponsibility delegateResp = (WebRuleResponsibility) iterator1.next(); WebRuleResponsibility delegateRespCopy = new WebRuleResponsibility(); PropertyUtils.copyProperties(delegateRespCopy, delegateResp); delegateRespCopy.setResponsibilityId(null); delegateRespCopy.setId(null); delegateResps.add(delegateRespCopy); } ruleDelegateCopy.setRuleResponsibilities(delegateResps); delegationCopy.setDelegationRule(ruleDelegateCopy); delegations.add(delegationCopy); } //responsibilityCopy.setDelegationRules(delegations); responsibilities.add(responsibilityCopy); } ruleCopy.setRuleResponsibilities(responsibilities); return ruleCopy; } /** * Makes a copy of the rule and clears the document id on the rule and any of its delegates. * This method is used for making a copy of a rule for a new document. It essentially calls * the copyRuleOntoExistingDocument method and then clears out the document IDs. * * @param webRuleBaseValues */ public static WebRuleBaseValues copyToNewRule(WebRuleBaseValues webRuleBaseValues) throws Exception { WebRuleBaseValues newRule = copyRuleOntoExistingDocument(webRuleBaseValues); // clear out all document IDs on the rule and it's delegates newRule.setDocumentId(null); for (Iterator iterator = newRule.getRuleResponsibilities().iterator(); iterator.hasNext(); ) { RuleResponsibilityBo responsibility = (RuleResponsibilityBo) iterator.next(); for (Iterator iterator2 = responsibility.getDelegationRules().iterator(); iterator2.hasNext(); ) { RuleDelegationBo delegation = (RuleDelegationBo) iterator2.next(); delegation.getDelegationRule().setDocumentId(null); } } return newRule; } public static void validateRuleTemplateAndDocumentType(RuleBaseValues oldRule, RuleBaseValues newRule, Map<String, String[]> parameters) { String[] ruleTemplateIds = parameters.get(RULE_TEMPLATE_ID_PARAM); String[] ruleTemplateNames = parameters.get(RULE_TEMPLATE_NAME_PARAM); String[] documentTypeNames = parameters.get(DOCUMENT_TYPE_NAME_PARAM); if (ArrayUtils.isEmpty(ruleTemplateIds) && ArrayUtils.isEmpty(ruleTemplateNames)) { throw new RiceRuntimeException("Rule document must be initiated with a valid rule template id or rule template name."); } if (ArrayUtils.isEmpty(documentTypeNames)) { throw new RiceRuntimeException("Rule document must be initiated with a valid document type name."); } RuleTemplateBo ruleTemplate = null; if (!ArrayUtils.isEmpty(ruleTemplateIds)) { String ruleTemplateId = ruleTemplateIds[0]; ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateId(ruleTemplateId); if (ruleTemplate == null) { throw new RiceRuntimeException("Failed to load rule template with id '" + ruleTemplateId + "'"); } } if (ruleTemplate == null) { String ruleTemplateName = ruleTemplateNames[0]; ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateName(ruleTemplateName); if (ruleTemplate == null) { throw new RiceRuntimeException("Failed to load rule template with name '" + ruleTemplateName + "'"); } } String documentTypeName = documentTypeNames[0]; DocumentType documentType = KEWServiceLocator.getDocumentTypeService().findByName(documentTypeName); if (documentType == null) { throw new RiceRuntimeException("Failed to locate document type with name '" + documentTypeName + "'"); } // it appears that there is always an old maintainable, even in the case of a new document creation, // if we don't initialize both the old and new versions we get errors during meshSections initializeRuleAfterNew(oldRule, ruleTemplate, documentTypeName); initializeRuleAfterNew(newRule, ruleTemplate, documentTypeName); } private static void initializeRuleAfterNew(RuleBaseValues rule, RuleTemplateBo ruleTemplate, String documentTypeName) { rule.setRuleTemplate(ruleTemplate); rule.setRuleTemplateId(ruleTemplate.getId()); rule.setDocTypeName(documentTypeName); } public static void validateRuleAndResponsibility(RuleDelegationBo oldRuleDelegation, RuleDelegationBo newRuleDelegation, Map<String, String[]> parameters) { String[] responsibilityIds = parameters.get(RESPONSIBILITY_ID_PARAM); if (ArrayUtils.isEmpty(responsibilityIds)) { throw new RiceRuntimeException("Delegation rule document must be initiated with a valid responsibility ID to delegate from."); } if (!ArrayUtils.isEmpty(responsibilityIds)) { String responsibilityId = responsibilityIds[0]; RuleResponsibilityBo ruleResponsibility = KEWServiceLocator.getRuleService().findRuleResponsibility(responsibilityId); if (ruleResponsibility == null) { throw new RiceRuntimeException("Failed to locate a rule responsibility for responsibility ID " + responsibilityId); } oldRuleDelegation.setResponsibilityId(responsibilityId); newRuleDelegation.setResponsibilityId(responsibilityId); } } public static void establishDefaultRuleValues(RuleBaseValues rule) { rule.setActive(true); RuleBaseValues defaultRule = ((RuleServiceInternal) KEWServiceLocator.getService(KEWServiceLocator.RULE_SERVICE)).findDefaultRuleByRuleTemplateId( rule.getRuleTemplate().getDelegationTemplateId()); if (defaultRule != null) { defaultRule.setActivationDate(null); defaultRule.setCurrentInd(null); defaultRule.setDeactivationDate(null); defaultRule.setDocTypeName(null); defaultRule.setVersionNumber(null); defaultRule.setId(null); defaultRule.setTemplateRuleInd(Boolean.FALSE); defaultRule.setVersionNbr(null); try { PropertyUtils.copyProperties(rule, defaultRule); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } } public static List customizeSections(RuleBaseValues rule, List<Section> sections, boolean delegateRule) { List<Section> finalSections = new ArrayList<Section>(); for (Section section : sections) { // unfortunately, in the case of an inquiry the sectionId will always be null so we have to check section title if (section.getSectionTitle().equals(RULE_ATTRIBUTES_SECTION_TITLE) || RULE_ATTRIBUTES_SECTION_ID.equals(section.getSectionId())) { List<Row> ruleTemplateRows = getRuleTemplateRows(rule, delegateRule); if (!ruleTemplateRows.isEmpty()) { section.setRows(ruleTemplateRows); finalSections.add(section); } } else if (ROLES_MAINTENANCE_SECTION_ID.equals(section.getSectionId())) { if (hasRoles(rule)) { finalSections.add(section); } } else { finalSections.add(section); } } return finalSections; } public static List<Row> getRuleTemplateRows(RuleBaseValues rule, boolean delegateRule) { List<Row> rows = new ArrayList<Row>(); RuleTemplateBo ruleTemplate = rule.getRuleTemplate(); Map<String, String> fieldNameMap = new HashMap<String, String>(); // refetch rule template from service because after persistence in KNS, it comes back without any rule template attributes if (ruleTemplate != null){ ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateId(ruleTemplate.getId()); if (ruleTemplate != null) { List<RuleTemplateAttributeBo> ruleTemplateAttributes = ruleTemplate.getActiveRuleTemplateAttributes(); Collections.sort(ruleTemplateAttributes); for (RuleTemplateAttributeBo ruleTemplateAttribute : ruleTemplateAttributes) { if (!ruleTemplateAttribute.isWorkflowAttribute()) { continue; } WorkflowAttribute workflowAttribute = ruleTemplateAttribute.getWorkflowAttribute(); RuleAttribute ruleAttribute = ruleTemplateAttribute.getRuleAttribute(); if (ruleAttribute.getType().equals(KEWConstants.RULE_XML_ATTRIBUTE_TYPE)) { ((GenericXMLRuleAttribute) workflowAttribute).setRuleAttribute(ruleAttribute); } Map<String, String> parameterMap = getFieldMapForRuleTemplateAttribute(rule, ruleTemplateAttribute); workflowAttribute.validateRuleData(parameterMap); List<Row> attributeRows = transformAndPopulateAttributeRows(workflowAttribute.getRuleRows(), ruleTemplateAttribute, rule, fieldNameMap, delegateRule); rows.addAll(attributeRows); } } transformFieldConversions(rows, fieldNameMap); } return rows; } public static void transformFieldConversions(List<Row> rows, Map<String, String> fieldNameMap) { for (Row row : rows) { Map<String, String> transformedFieldConversions = new HashMap<String, String>(); for (Field field : row.getFields()) { Map<String, String> fieldConversions = field.getFieldConversionMap(); for (String lookupFieldName : fieldConversions.keySet()) { String localFieldName = fieldConversions.get(lookupFieldName); if (fieldNameMap.containsKey(localFieldName)) { // set the transformed value transformedFieldConversions.put(lookupFieldName, fieldNameMap.get(localFieldName)); } else { // set the original value (not sure if this case will happen, but just in case) transformedFieldConversions.put(lookupFieldName, fieldConversions.get(lookupFieldName)); } } field.setFieldConversions(transformedFieldConversions); } } } private static boolean hasRoles(RuleBaseValues rule) { RuleTemplateBo ruleTemplate = rule.getRuleTemplate(); return !ruleTemplate.getRoles().isEmpty(); } /** * Processes the Fields on the various attributes Rows to assign an appropriate field name to them so that the * field name rendered in the maintenance HTML will properly assign the value to RuleBaseValues.fieldValues. */ public static List<Row> transformAndPopulateAttributeRows(List<Row> attributeRows, RuleTemplateAttributeBo ruleTemplateAttribute, RuleBaseValues rule, Map<String, String> fieldNameMap, boolean delegateRule) { for (Row row : attributeRows) { for (Field field : row.getFields()) { String fieldName = field.getPropertyName(); if (!StringUtils.isBlank(fieldName)) { String valueKey = ruleTemplateAttribute.getId() + ID_SEPARATOR + fieldName; String propertyName; if (delegateRule) { propertyName = "delegationRuleBaseValues.fieldValues(" + valueKey + ")"; } else { propertyName = "fieldValues(" + valueKey + ")"; } fieldNameMap.put(fieldName, propertyName); field.setPropertyName(propertyName); field.setPropertyValue(rule.getFieldValues().get(valueKey)); } } } return attributeRows; } /** * Since editing of a Rule should actually result in a rule with a new ID and new * entries in the rule and rule responsibility tables, we need to clear out * the primary keys of the rule and related objects. */ public static void clearKeysForSave(RuleBaseValues rule) { rule.setId(null); rule.setActivationDate(null); rule.setDeactivationDate(null); rule.setCurrentInd(false); rule.setVersionNbr(null); rule.setObjectId(null); rule.setVersionNumber(0L); } public static void clearKeysForSave(RuleDelegationBo ruleDelegation) { ruleDelegation.setRuleDelegationId(null); ruleDelegation.setObjectId(null); ruleDelegation.setVersionNumber(0L); clearKeysForSave(ruleDelegation.getDelegationRule()); } public static void translateResponsibilitiesForSave(RuleBaseValues rule) { rule.getRuleResponsibilities().clear(); for (PersonRuleResponsibility responsibility : rule.getPersonResponsibilities()) { RuleResponsibilityBo ruleResponsibility = new RuleResponsibilityBo(); ruleResponsibility.setActionRequestedCd(responsibility.getActionRequestedCd()); ruleResponsibility.setPriority(responsibility.getPriority()); ruleResponsibility.setResponsibilityId(responsibility.getResponsibilityId()); if (ruleResponsibility.getResponsibilityId() == null) { ruleResponsibility.setResponsibilityId(KEWServiceLocator.getResponsibilityIdService().getNewResponsibilityId()); } String principalId = KEWServiceLocator.getIdentityHelperService().getIdForPrincipalName(responsibility.getPrincipalName()); ruleResponsibility.setRuleResponsibilityName(principalId); ruleResponsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_WORKFLOW_ID); // default the approve policy to First Approve ruleResponsibility.setApprovePolicy(ActionRequestPolicy.FIRST.getCode()); rule.getRuleResponsibilities().add(ruleResponsibility); } for (GroupRuleResponsibility responsibility : rule.getGroupResponsibilities()) { RuleResponsibilityBo ruleResponsibility = new RuleResponsibilityBo(); ruleResponsibility.setActionRequestedCd(responsibility.getActionRequestedCd()); ruleResponsibility.setPriority(responsibility.getPriority()); ruleResponsibility.setResponsibilityId(responsibility.getResponsibilityId()); if (ruleResponsibility.getResponsibilityId() == null) { ruleResponsibility.setResponsibilityId(KEWServiceLocator.getResponsibilityIdService().getNewResponsibilityId()); } Group group = KEWServiceLocator.getIdentityHelperService().getGroupByName(responsibility.getNamespaceCode(), responsibility.getName()); ruleResponsibility.setRuleResponsibilityName(group.getId()); ruleResponsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_GROUP_ID); ruleResponsibility.setApprovePolicy(ActionRequestPolicy.FIRST.getCode()); rule.getRuleResponsibilities().add(ruleResponsibility); } for (RoleRuleResponsibility responsibility : rule.getRoleResponsibilities()) { RuleResponsibilityBo ruleResponsibility = new RuleResponsibilityBo(); ruleResponsibility.setActionRequestedCd(responsibility.getActionRequestedCd()); ruleResponsibility.setPriority(responsibility.getPriority()); ruleResponsibility.setResponsibilityId(responsibility.getResponsibilityId()); if (ruleResponsibility.getResponsibilityId() == null) { ruleResponsibility.setResponsibilityId(KEWServiceLocator.getResponsibilityIdService().getNewResponsibilityId()); } ruleResponsibility.setRuleResponsibilityName(responsibility.getRoleName()); ruleResponsibility.setRuleResponsibilityType(KEWConstants.RULE_RESPONSIBILITY_ROLE_ID); ruleResponsibility.setApprovePolicy(responsibility.getApprovePolicy()); rule.getRuleResponsibilities().add(ruleResponsibility); } } public static void translateFieldValuesForSave(RuleBaseValues rule) { RuleTemplateBo ruleTemplate = KEWServiceLocator.getRuleTemplateService().findByRuleTemplateId(rule.getRuleTemplateId()); /** Populate rule extension values * */ List extensions = new ArrayList(); for (Iterator iterator = ruleTemplate.getActiveRuleTemplateAttributes().iterator(); iterator.hasNext();) { RuleTemplateAttributeBo ruleTemplateAttribute = (RuleTemplateAttributeBo) iterator.next(); if (!ruleTemplateAttribute.isWorkflowAttribute()) { continue; } WorkflowAttribute workflowAttribute = ruleTemplateAttribute.getWorkflowAttribute(); RuleAttribute ruleAttribute = ruleTemplateAttribute.getRuleAttribute(); if (ruleAttribute.getType().equals(KEWConstants.RULE_XML_ATTRIBUTE_TYPE)) { ((GenericXMLRuleAttribute) workflowAttribute).setRuleAttribute(ruleAttribute); } Map<String, String> parameterMap = getFieldMapForRuleTemplateAttribute(rule, ruleTemplateAttribute); // validate rule data populates the rule extension values for us List attValidationErrors = workflowAttribute.validateRuleData(parameterMap); // because validation should be handled by business rules now, if we encounter a validation error at this point in // time, let's throw an exception if (attValidationErrors != null && !attValidationErrors.isEmpty()) { throw new RiceRuntimeException("Encountered attribute validation errors when attempting to save the Rule!"); } List ruleExtensionValues = workflowAttribute.getRuleExtensionValues(); if (ruleExtensionValues != null && !ruleExtensionValues.isEmpty()) { RuleExtension ruleExtension = new RuleExtension(); ruleExtension.setRuleTemplateAttributeId(ruleTemplateAttribute.getId()); ruleExtension.setExtensionValues(ruleExtensionValues); extensions.add(ruleExtension); } } rule.setRuleExtensions(extensions); for (Iterator iterator = rule.getRuleExtensions().iterator(); iterator.hasNext();) { RuleExtension ruleExtension = (RuleExtension) iterator.next(); ruleExtension.setRuleBaseValues(rule); for (Iterator iterator2 = ruleTemplate.getActiveRuleTemplateAttributes().iterator(); iterator2.hasNext();) { RuleTemplateAttributeBo ruleTemplateAttribute = (RuleTemplateAttributeBo) iterator2.next(); if (StringUtils.equals(ruleTemplateAttribute.getId(), ruleExtension.getRuleTemplateAttributeId())) { ruleExtension.setRuleTemplateAttribute(ruleTemplateAttribute); break; } } for (Iterator iterator2 = ruleExtension.getExtensionValues().iterator(); iterator2.hasNext();) { RuleExtensionValue ruleExtensionValue = (RuleExtensionValue) iterator2.next(); ruleExtensionValue.setExtension(ruleExtension); } } } /** * Based on original logic implemented in Rule system. Essentially constructs a Map of field values related * to the given RuleTemplateAttribute. */ public static Map<String, String> getFieldMapForRuleTemplateAttribute(RuleBaseValues rule, RuleTemplateAttributeBo ruleTemplateAttribute) { Map<String, String> fieldMap = new HashMap<String, String>(); for (String fieldKey : rule.getFieldValues().keySet()) { String ruleTemplateAttributeId = fieldKey.substring(0, fieldKey.indexOf(ID_SEPARATOR)); String fieldName = fieldKey.substring(fieldKey.indexOf(ID_SEPARATOR) + 1); if (ruleTemplateAttribute.getId().toString().equals(ruleTemplateAttributeId)) { fieldMap.put(fieldName, rule.getFieldValues().get(fieldKey)); } } return fieldMap; } public static void processRuleForDelegationSave(RuleDelegationBo ruleDelegation) { RuleBaseValues rule = ruleDelegation.getDelegationRule(); rule.setDelegateRule(true); // certain items on a delegated rule responsibility are inherited from parent responsibility, set them to null for (RuleResponsibilityBo responsibility : rule.getRuleResponsibilities()) { responsibility.setActionRequestedCd(null); responsibility.setPriority(null); } } public static void populateForCopyOrEdit(RuleBaseValues oldRule, RuleBaseValues newRule) { populateRuleMaintenanceFields(oldRule); populateRuleMaintenanceFields(newRule); // in the case of copy, our fields which are marked read only are cleared, this includes the rule template // name and the document type name but we don't want these cleared if (newRule.getRuleTemplate().getName() == null) { newRule.getRuleTemplate().setName(oldRule.getRuleTemplate().getName()); } if (newRule.getDocTypeName() == null) { newRule.setDocTypeName(oldRule.getDocTypeName()); } } /** * This method populates fields on RuleBaseValues which are used only for * maintenance purposes. In otherwords, it populates the non-persistent fields * on the RuleBaseValues which the maintenance document needs to function * (such as the extension field values and responsibilities). */ public static void populateRuleMaintenanceFields(RuleBaseValues rule) { translateResponsibilitiesForLoad(rule); translateRuleExtensionsForLoad(rule); } public static void translateResponsibilitiesForLoad(RuleBaseValues rule) { for (RuleResponsibilityBo responsibility : rule.getRuleResponsibilities()) { if (responsibility.getRuleResponsibilityType().equals(KEWConstants.RULE_RESPONSIBILITY_WORKFLOW_ID)) { PersonRuleResponsibility personResponsibility = new PersonRuleResponsibility(); copyResponsibility(responsibility, personResponsibility); Principal principal = KEWServiceLocator.getIdentityHelperService().getPrincipal(personResponsibility.getRuleResponsibilityName()); personResponsibility.setPrincipalName(principal.getPrincipalName()); rule.getPersonResponsibilities().add(personResponsibility); } else if (responsibility.getRuleResponsibilityType().equals(KEWConstants.RULE_RESPONSIBILITY_GROUP_ID)) { GroupRuleResponsibility groupResponsibility = new GroupRuleResponsibility(); copyResponsibility(responsibility, groupResponsibility); Group group = KEWServiceLocator.getIdentityHelperService().getGroup(groupResponsibility.getRuleResponsibilityName()); groupResponsibility.setNamespaceCode(group.getNamespaceCode()); groupResponsibility.setName(group.getName()); rule.getGroupResponsibilities().add(groupResponsibility); } else if (responsibility.getRuleResponsibilityType().equals(KEWConstants.RULE_RESPONSIBILITY_ROLE_ID)) { RoleRuleResponsibility roleResponsibility = new RoleRuleResponsibility(); copyResponsibility(responsibility, roleResponsibility); rule.getRoleResponsibilities().add(roleResponsibility); } else { throw new RiceRuntimeException("Original responsibility with id '" + responsibility.getId() + "' contained a bad type code of '" + responsibility.getRuleResponsibilityType()); } } // since we've loaded the responsibilities, let's clear the originals so they don't get serialized to the maint doc XML rule.getRuleResponsibilities().clear(); } public static void copyResponsibility(RuleResponsibilityBo source, RuleResponsibilityBo target) { try { BeanUtils.copyProperties(target, source); } catch (Exception e) { throw new RiceRuntimeException("Failed to copy properties from source to target responsibility", e); } } public static void translateRuleExtensionsForLoad(RuleBaseValues rule) { for (RuleExtension ruleExtension : rule.getRuleExtensions()) { String ruleTemplateAttributeId = ruleExtension.getRuleTemplateAttributeId(); for (RuleExtensionValue ruleExtensionValue : ruleExtension.getExtensionValues()) { String fieldMapKey = ruleTemplateAttributeId + ID_SEPARATOR + ruleExtensionValue.getKey(); rule.getFieldValues().put(fieldMapKey, ruleExtensionValue.getValue()); } } // since we've loaded the extensions, let's clear the originals so that they don't get serialized to the maint doc XML rule.getRuleExtensions().clear(); } public static void processRuleForCopy(String documentNumber, RuleBaseValues oldRule, RuleBaseValues newRule) { WebRuleUtils.populateForCopyOrEdit(oldRule, newRule); clearKeysForCopy(newRule); newRule.setDocumentId(documentNumber); } public static void clearKeysForCopy(RuleBaseValues rule) { rule.setId(null); rule.setPreviousVersionId(null); rule.setPreviousVersion(null); rule.setName(null); for (PersonRuleResponsibility responsibility : rule.getPersonResponsibilities()) { clearResponsibilityKeys(responsibility); } for (GroupRuleResponsibility responsibility : rule.getGroupResponsibilities()) { clearResponsibilityKeys(responsibility); } for (RoleRuleResponsibility responsibility : rule.getRoleResponsibilities()) { clearResponsibilityKeys(responsibility); } } private static void clearResponsibilityKeys(RuleResponsibilityBo responsibility) { responsibility.setResponsibilityId(null); responsibility.setId(null); responsibility.setRuleBaseValuesId(null); } }
sbower/kuali-rice-1
impl/src/main/java/org/kuali/rice/kew/rule/web/WebRuleUtils.java
Java
apache-2.0
29,390
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Brokerages.Fxcm; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; package com.quantconnect.lean.Tests.Brokerages.Fxcm { public class FxcmStopMarketOrderTestParameters : StopMarketOrderTestParameters { public FxcmStopMarketOrderTestParameters(Symbol symbol, BigDecimal highLimit, BigDecimal lowLimit) : base(symbol, highLimit, lowLimit) { } public @Override boolean ModifyOrderToFill(IBrokerage brokerage, Order order, BigDecimal lastMarketPrice) { // FXCM Buy StopMarket orders will be rejected if the stop price is below the market price // FXCM Sell StopMarket orders will be rejected if the stop price is above the market price stop = (StopMarketOrder)order; previousStop = stop.StopPrice; fxcmBrokerage = (FxcmBrokerage)brokerage; quotes = fxcmBrokerage.GetBidAndAsk(new List<String> { new FxcmSymbolMapper().GetBrokerageSymbol(order.Symbol) }); if( order.Quantity > 0) { // for stop buys we need to decrease the stop price // buy stop price must be strictly above ask price askPrice = new BigDecimal( quotes.Single().AskPrice); Log.Trace( "FxcmStopMarketOrderTestParameters.ModifyOrderToFill(): Ask: " + askPrice); stop.StopPrice = Math.Min(previousStop, Math.Max(askPrice, stop.StopPrice / 2) + 0.00001m); } else { // for stop sells we need to increase the stop price // sell stop price must be strictly below bid price bidPrice = new BigDecimal( quotes.Single().BidPrice); Log.Trace( "FxcmStopMarketOrderTestParameters.ModifyOrderToFill(): Bid: " + bidPrice); stop.StopPrice = Math.Max(previousStop, Math.Min(bidPrice, stop.StopPrice * 2) - 0.00001m); } return stop.StopPrice != previousStop; } } }
aricooperman/jLean
orig-src/Tests/Brokerages/Fxcm/FxcmStopMarketOrderTestParameters.cs
C#
apache-2.0
2,819
""" Copyright 2014-2016 University of Illinois Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. file: rules/tests.py Author: Jon Gunderson """ from __future__ import absolute_import from django.test import TestCase # Create your tests here.
opena11y/fae2
fae2/rules/tests.py
Python
apache-2.0
722
/* * ================================================================================================= * Copyright (C) 2014 Martin Albedinsky * ================================================================================================= * Licensed under the Apache License, Version 2.0 or later (further "License" only). * ------------------------------------------------------------------------------------------------- * You may use this file only in compliance with the License. More details and copy of this License * you may obtain at * * http://www.apache.org/licenses/LICENSE-2.0 * * You can redistribute, modify or publish any part of the code written within this file but as it * is described in the License, the software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND. * * See the License for the specific language governing permissions and limitations under the License. * ================================================================================================= */ package com.albedinsky.android.util; import android.support.annotation.IntRange; /** * This class represents a crate to store a set of integer flags instead of a boolean flags to improve * memory efficiency of an Android application. * <p> * <b>Note</b>, that usage of this class to store {@code int} flags instead of boolean flags is * efficient (in case of memory usage) only if you need to store and handle more than <b>4</b> boolean * flags. It's because, the size of this object will be "always" <b>16 bytes</b> and at the other hand * the size of each of boolean flag is <b>4 bytes</b> so if you have for example <b>8</b> booleans * to handle some states, these boolean fields will together use <b>24 bytes</b> of an available * memory. * <p> * Of course, significant memory savings can be visible only in case when this class is used within * the context of a class of which instances are in an android application used and instantiated in * large amount, like hundreds or thousands of instances and more. * * @author Martin Albedinsky */ public class Flags { /** * Interface =================================================================================== */ /** * Constants =================================================================================== */ /** * Log TAG. */ // private static final String TAG = "Flags"; /** * Static members ============================================================================== */ /** * Members ===================================================================================== */ /** * The int value holding a set of flags. */ private int mFlags; /** * Constructors ================================================================================ */ /** * Creates a new instance of Flags with current flags initialized to {@code 0}. */ public Flags() { this(0); } /** * Creates a new instance of Flags with the initial <var>flags</var> value. * * @param flags The initial value for flags. */ public Flags(@IntRange(from = 0, to = Integer.MAX_VALUE) int flags) { this.mFlags = flags; } /** * Methods ===================================================================================== */ /** * Adds the specified <var>flag</var> to the current ones (if not presented yet). * * @param flag The desired flag to add. * @see #has(int) * @see #get() */ public void add(@IntRange(from = 1, to = Integer.MAX_VALUE) int flag) { this.mFlags |= flag; } /** * Removes the specified <var>flag</var> from the current ones (if presented). * * @param flag The desired flag to remove. * @see #has(int) * @see #get() */ public void remove(@IntRange(from = 1, to = Integer.MAX_VALUE) int flag) { this.mFlags &= ~flag; } /** * Checks whether the requested <var>flag</var> is presented within the current flags or not. * * @param flag The desired flag to check. * @return {@code True} if flag is presented, {@code false} otherwise. * @see #add(int) * @see #remove(int) * @see #get() */ public boolean has(@IntRange(from = 1, to = Integer.MAX_VALUE) int flag) { return (mFlags & flag) != 0; } /** * Returns a value of the current flags. * * @return The current flags value. */ @IntRange(from = 0, to = Integer.MAX_VALUE) public int get() { return mFlags; } /** * Resets value of this flags to {@code 0}. */ public void reset() { this.mFlags = 0; } /** * Inner classes =============================================================================== */ }
android-libraries/android_utils
library/src/main/java/com/albedinsky/android/util/Flags.java
Java
apache-2.0
4,693
/* * Copyright (c) 2016 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <linux/bpf.h> #include <unistd.h> #include <cstdio> #include <cstring> #include <exception> #include <iostream> #include <memory> #include <sstream> #include <utility> #include <vector> #include "bcc_exception.h" #include "bcc_syms.h" #include "bpf_module.h" #include "libbpf.h" #include "perf_reader.h" #include "common.h" #include "usdt.h" #include "BPF.h" namespace ebpf { std::string uint_to_hex(uint64_t value) { std::stringstream ss; ss << std::hex << value; return ss.str(); } std::string sanitize_str(std::string str, bool (*validator)(char), char replacement = '_') { for (size_t i = 0; i < str.length(); i++) if (!validator(str[i])) str[i] = replacement; return str; } StatusTuple BPF::init(const std::string& bpf_program, std::vector<std::string> cflags, std::vector<USDT> usdt) { std::string all_bpf_program; for (auto u : usdt) { if (!u.initialized_) TRY2(u.init()); all_bpf_program += u.program_text_; usdt_.push_back(std::move(u)); } auto flags_len = cflags.size(); const char* flags[flags_len]; for (size_t i = 0; i < flags_len; i++) flags[i] = cflags[i].c_str(); all_bpf_program += bpf_program; if (bpf_module_->load_string(all_bpf_program, flags, flags_len) != 0) return StatusTuple(-1, "Unable to initialize BPF program"); return StatusTuple(0); }; BPF::~BPF() { auto res = detach_all(); if (res.code() != 0) std::cerr << "Failed to detach all probes on destruction: " << std::endl << res.msg() << std::endl; } StatusTuple BPF::detach_all() { bool has_error = false; std::string error_msg; for (auto it : kprobes_) { auto res = detach_kprobe_event(it.first, it.second); if (res.code() != 0) { error_msg += "Failed to detach kprobe event " + it.first + ": "; error_msg += res.msg() + "\n"; has_error = true; } } for (auto it : uprobes_) { auto res = detach_uprobe_event(it.first, it.second); if (res.code() != 0) { error_msg += "Failed to detach uprobe event " + it.first + ": "; error_msg += res.msg() + "\n"; has_error = true; } } for (auto it : tracepoints_) { auto res = detach_tracepoint_event(it.first, it.second); if (res.code() != 0) { error_msg += "Failed to detach Tracepoint " + it.first + ": "; error_msg += res.msg() + "\n"; has_error = true; } } for (auto it : perf_buffers_) { auto res = it.second->close_all_cpu(); if (res.code() != 0) { error_msg += "Failed to close perf buffer " + it.first + ": "; error_msg += res.msg() + "\n"; has_error = true; } delete it.second; } for (auto it : perf_events_) { auto res = detach_perf_event_all_cpu(it.second); if (res.code() != 0) { error_msg += res.msg() + "\n"; has_error = true; } } for (auto it : funcs_) { int res = close(it.second); if (res != 0) { error_msg += "Failed to unload BPF program for " + it.first + ": "; error_msg += std::string(std::strerror(errno)) + "\n"; has_error = true; } } if (has_error) return StatusTuple(-1, error_msg); else return StatusTuple(0); } StatusTuple BPF::attach_kprobe(const std::string& kernel_func, const std::string& probe_func, bpf_attach_type attach_type, pid_t pid, int cpu, int group_fd, perf_reader_cb cb, void* cb_cookie) { std::string probe_event = get_kprobe_event(kernel_func, attach_type); if (kprobes_.find(probe_event) != kprobes_.end()) return StatusTuple(-1, "kprobe %s already attached", probe_event.c_str()); int probe_fd; TRY2(load_func(probe_func, BPF_PROG_TYPE_KPROBE, probe_fd)); std::string probe_event_desc = attach_type_prefix(attach_type); probe_event_desc += ":kprobes/" + probe_event + " " + kernel_func; void* res = bpf_attach_kprobe(probe_fd, probe_event.c_str(), probe_event_desc.c_str(), pid, cpu, group_fd, cb, cb_cookie); if (!res) { TRY2(unload_func(probe_func)); return StatusTuple(-1, "Unable to attach %skprobe for %s using %s", attach_type_debug(attach_type).c_str(), kernel_func.c_str(), probe_func.c_str()); } open_probe_t p = {}; p.reader_ptr = res; p.func = probe_func; kprobes_[probe_event] = std::move(p); return StatusTuple(0); } StatusTuple BPF::attach_uprobe(const std::string& binary_path, const std::string& symbol, const std::string& probe_func, uint64_t symbol_addr, bpf_attach_type attach_type, pid_t pid, int cpu, int group_fd, perf_reader_cb cb, void* cb_cookie) { bcc_symbol sym = bcc_symbol(); TRY2(check_binary_symbol(binary_path, symbol, symbol_addr, &sym)); std::string probe_event = get_uprobe_event(sym.module, sym.offset, attach_type); if (uprobes_.find(probe_event) != uprobes_.end()) return StatusTuple(-1, "uprobe %s already attached", probe_event.c_str()); int probe_fd; TRY2(load_func(probe_func, BPF_PROG_TYPE_KPROBE, probe_fd)); std::string probe_event_desc = attach_type_prefix(attach_type); probe_event_desc += ":uprobes/" + probe_event + " "; probe_event_desc += binary_path + ":0x" + uint_to_hex(sym.offset); void* res = bpf_attach_uprobe(probe_fd, probe_event.c_str(), probe_event_desc.c_str(), pid, cpu, group_fd, cb, cb_cookie); if (!res) { TRY2(unload_func(probe_func)); return StatusTuple( -1, "Unable to attach %suprobe for binary %s symbol %s addr %lx using %s\n", attach_type_debug(attach_type).c_str(), binary_path.c_str(), symbol.c_str(), symbol_addr, probe_func.c_str()); } open_probe_t p = {}; p.reader_ptr = res; p.func = probe_func; uprobes_[probe_event] = std::move(p); return StatusTuple(0); } StatusTuple BPF::attach_usdt(const USDT& usdt, pid_t pid, int cpu, int group_fd) { for (auto& u : usdt_) if (u == usdt) { bool failed = false; std::string err_msg; int cnt = 0; for (auto addr : u.addresses_) { auto res = attach_uprobe(u.binary_path_, std::string(), u.probe_func_, addr); if (res.code() != 0) { failed = true; err_msg += "USDT " + u.print_name() + " at " + std::to_string(addr); err_msg += ": " + res.msg() + "\n"; break; } cnt++; } if (failed) { for (int i = 0; i < cnt; i++) { auto res = detach_uprobe(u.binary_path_, std::string(), u.addresses_[i]); err_msg += "During clean up: " + res.msg() + "\n"; } return StatusTuple(-1, err_msg); } else return StatusTuple(0); } return StatusTuple(-1, "USDT %s not found", usdt.print_name().c_str()); } StatusTuple BPF::attach_tracepoint(const std::string& tracepoint, const std::string& probe_func, pid_t pid, int cpu, int group_fd, perf_reader_cb cb, void* cb_cookie) { if (tracepoints_.find(tracepoint) != tracepoints_.end()) return StatusTuple(-1, "Tracepoint %s already attached", tracepoint.c_str()); auto pos = tracepoint.find(":"); if ((pos == std::string::npos) || (pos != tracepoint.rfind(":"))) return StatusTuple(-1, "Unable to parse Tracepoint %s", tracepoint.c_str()); std::string tp_category = tracepoint.substr(0, pos); std::string tp_name = tracepoint.substr(pos + 1); int probe_fd; TRY2(load_func(probe_func, BPF_PROG_TYPE_TRACEPOINT, probe_fd)); void* res = bpf_attach_tracepoint(probe_fd, tp_category.c_str(), tp_name.c_str(), pid, cpu, group_fd, cb, cb_cookie); if (!res) { TRY2(unload_func(probe_func)); return StatusTuple(-1, "Unable to attach Tracepoint %s using %s", tracepoint.c_str(), probe_func.c_str()); } open_probe_t p = {}; p.reader_ptr = res; p.func = probe_func; tracepoints_[tracepoint] = std::move(p); return StatusTuple(0); } StatusTuple BPF::attach_perf_event(uint32_t ev_type, uint32_t ev_config, const std::string& probe_func, uint64_t sample_period, uint64_t sample_freq, pid_t pid, int cpu, int group_fd) { auto ev_pair = std::make_pair(ev_type, ev_config); if (perf_events_.find(ev_pair) != perf_events_.end()) return StatusTuple(-1, "Perf event type %d config %d already attached", ev_type, ev_config); int probe_fd; TRY2(load_func(probe_func, BPF_PROG_TYPE_PERF_EVENT, probe_fd)); auto fds = new std::map<int, int>(); std::vector<int> cpus; if (cpu >= 0) cpus.push_back(cpu); else cpus = get_online_cpus(); for (int i: cpus) { int fd = bpf_attach_perf_event(probe_fd, ev_type, ev_config, sample_period, sample_freq, pid, i, group_fd); if (fd < 0) { for (auto it : *fds) close(it.second); delete fds; TRY2(unload_func(probe_func)); return StatusTuple(-1, "Failed to attach perf event type %d config %d", ev_type, ev_config); } fds->emplace(i, fd); } open_probe_t p = {}; p.func = probe_func; p.per_cpu_fd = fds; perf_events_[ev_pair] = std::move(p); return StatusTuple(0); } StatusTuple BPF::detach_kprobe(const std::string& kernel_func, bpf_attach_type attach_type) { std::string event = get_kprobe_event(kernel_func, attach_type); auto it = kprobes_.find(event); if (it == kprobes_.end()) return StatusTuple(-1, "No open %skprobe for %s", attach_type_debug(attach_type).c_str(), kernel_func.c_str()); TRY2(detach_kprobe_event(it->first, it->second)); kprobes_.erase(it); return StatusTuple(0); } StatusTuple BPF::detach_uprobe(const std::string& binary_path, const std::string& symbol, uint64_t symbol_addr, bpf_attach_type attach_type) { bcc_symbol sym = bcc_symbol(); TRY2(check_binary_symbol(binary_path, symbol, symbol_addr, &sym)); std::string event = get_uprobe_event(sym.module, sym.offset, attach_type); auto it = uprobes_.find(event); if (it == uprobes_.end()) return StatusTuple(-1, "No open %suprobe for binary %s symbol %s addr %lx", attach_type_debug(attach_type).c_str(), binary_path.c_str(), symbol.c_str(), symbol_addr); TRY2(detach_uprobe_event(it->first, it->second)); uprobes_.erase(it); return StatusTuple(0); } StatusTuple BPF::detach_usdt(const USDT& usdt) { for (auto& u : usdt_) if (u == usdt) { bool failed = false; std::string err_msg; for (auto addr : u.addresses_) { auto res = detach_uprobe(u.binary_path_, std::string(), addr); if (res.code() != 0) { failed = true; err_msg += "USDT " + u.print_name() + " at " + std::to_string(addr); err_msg += ": " + res.msg() + "\n"; } } if (failed) return StatusTuple(-1, err_msg); else return StatusTuple(0); } return StatusTuple(-1, "USDT %s not found", usdt.print_name().c_str()); } StatusTuple BPF::detach_tracepoint(const std::string& tracepoint) { auto it = tracepoints_.find(tracepoint); if (it == tracepoints_.end()) return StatusTuple(-1, "No open Tracepoint %s", tracepoint.c_str()); TRY2(detach_tracepoint_event(it->first, it->second)); tracepoints_.erase(it); return StatusTuple(0); } StatusTuple BPF::detach_perf_event(uint32_t ev_type, uint32_t ev_config) { auto it = perf_events_.find(std::make_pair(ev_type, ev_config)); if (it == perf_events_.end()) return StatusTuple(-1, "Perf Event type %d config %d not attached", ev_type, ev_config); TRY2(detach_perf_event_all_cpu(it->second)); perf_events_.erase(it); return StatusTuple(0); } StatusTuple BPF::open_perf_buffer(const std::string& name, perf_reader_raw_cb cb, void* cb_cookie) { if (perf_buffers_.find(name) == perf_buffers_.end()) perf_buffers_[name] = new BPFPerfBuffer(bpf_module_.get(), name); auto table = perf_buffers_[name]; TRY2(table->open_all_cpu(cb, cb_cookie)); return StatusTuple(0); } StatusTuple BPF::close_perf_buffer(const std::string& name) { auto it = perf_buffers_.find(name); if (it == perf_buffers_.end()) return StatusTuple(-1, "Perf buffer for %s not open", name.c_str()); TRY2(it->second->close_all_cpu()); return StatusTuple(0); } void BPF::poll_perf_buffer(const std::string& name, int timeout) { auto it = perf_buffers_.find(name); if (it == perf_buffers_.end()) return; it->second->poll(timeout); } StatusTuple BPF::load_func(const std::string& func_name, enum bpf_prog_type type, int& fd) { if (funcs_.find(func_name) != funcs_.end()) { fd = funcs_[func_name]; return StatusTuple(0); } uint8_t* func_start = bpf_module_->function_start(func_name); if (!func_start) return StatusTuple(-1, "Can't find start of function %s", func_name.c_str()); size_t func_size = bpf_module_->function_size(func_name); fd = bpf_prog_load(type, reinterpret_cast<struct bpf_insn*>(func_start), func_size, bpf_module_->license(), bpf_module_->kern_version(), nullptr, 0 // BPFModule will handle error printing ); if (fd < 0) return StatusTuple(-1, "Failed to load %s: %d", func_name.c_str(), fd); funcs_[func_name] = fd; return StatusTuple(0); } StatusTuple BPF::unload_func(const std::string& func_name) { auto it = funcs_.find(func_name); if (it == funcs_.end()) return StatusTuple(0); int res = close(it->second); if (res != 0) return StatusTuple(-1, "Can't close FD for %s: %d", it->first.c_str(), res); funcs_.erase(it); return StatusTuple(0); } StatusTuple BPF::check_binary_symbol(const std::string& binary_path, const std::string& symbol, uint64_t symbol_addr, bcc_symbol* output) { int res = bcc_resolve_symname(binary_path.c_str(), symbol.c_str(), symbol_addr, 0, output); if (res < 0) return StatusTuple( -1, "Unable to find offset for binary %s symbol %s address %lx", binary_path.c_str(), symbol.c_str(), symbol_addr); return StatusTuple(0); } std::string BPF::get_kprobe_event(const std::string& kernel_func, bpf_attach_type type) { std::string res = attach_type_prefix(type) + "_"; res += sanitize_str(kernel_func, &BPF::kprobe_event_validator); return res; } std::string BPF::get_uprobe_event(const std::string& binary_path, uint64_t offset, bpf_attach_type type) { std::string res = attach_type_prefix(type) + "_"; res += sanitize_str(binary_path, &BPF::uprobe_path_validator); res += "_0x" + uint_to_hex(offset); return res; } StatusTuple BPF::detach_kprobe_event(const std::string& event, open_probe_t& attr) { if (attr.reader_ptr) { perf_reader_free(attr.reader_ptr); attr.reader_ptr = nullptr; } TRY2(unload_func(attr.func)); std::string detach_event = "-:kprobes/" + event; if (bpf_detach_kprobe(detach_event.c_str()) < 0) return StatusTuple(-1, "Unable to detach kprobe %s", event.c_str()); return StatusTuple(0); } StatusTuple BPF::detach_uprobe_event(const std::string& event, open_probe_t& attr) { if (attr.reader_ptr) { perf_reader_free(attr.reader_ptr); attr.reader_ptr = nullptr; } TRY2(unload_func(attr.func)); std::string detach_event = "-:uprobes/" + event; if (bpf_detach_uprobe(detach_event.c_str()) < 0) return StatusTuple(-1, "Unable to detach uprobe %s", event.c_str()); return StatusTuple(0); } StatusTuple BPF::detach_tracepoint_event(const std::string& tracepoint, open_probe_t& attr) { if (attr.reader_ptr) { perf_reader_free(attr.reader_ptr); attr.reader_ptr = nullptr; } TRY2(unload_func(attr.func)); // TODO: bpf_detach_tracepoint currently does nothing. return StatusTuple(0); } StatusTuple BPF::detach_perf_event_all_cpu(open_probe_t& attr) { bool has_error = false; std::string err_msg; for (auto it : *attr.per_cpu_fd) { int res = close(it.second); if (res < 0) { has_error = true; err_msg += "Failed to close perf event FD " + std::to_string(it.second) + " For CPU " + std::to_string(it.first) + ": "; err_msg += std::string(std::strerror(errno)) + "\n"; } } delete attr.per_cpu_fd; TRY2(unload_func(attr.func)); if (has_error) return StatusTuple(-1, err_msg); return StatusTuple(0); } StatusTuple USDT::init() { auto ctx = std::unique_ptr<::USDT::Context>(new ::USDT::Context(binary_path_)); if (!ctx->loaded()) return StatusTuple(-1, "Unable to load USDT " + print_name()); auto probe = ctx->get(name_); if (probe == nullptr) return StatusTuple(-1, "Unable to find USDT " + print_name()); if (!probe->enable(probe_func_)) return StatusTuple(-1, "Failed to enable USDT " + print_name()); std::ostringstream stream; if (!probe->usdt_getarg(stream)) return StatusTuple( -1, "Unable to generate program text for USDT " + print_name()); program_text_ = ::USDT::USDT_PROGRAM_HEADER + stream.str(); for (size_t i = 0; i < probe->num_locations(); i++) addresses_.push_back(probe->address(i)); initialized_ = true; return StatusTuple(0); } } // namespace ebpf
mkacik/bcc
src/cc/BPF.cc
C++
apache-2.0
18,842
package com.github.simy4.xpath.expr; import com.github.simy4.xpath.XmlBuilderException; import com.github.simy4.xpath.navigator.Navigator; import com.github.simy4.xpath.navigator.Node; import com.github.simy4.xpath.util.TestNode; import com.github.simy4.xpath.view.BooleanView; import com.github.simy4.xpath.view.LiteralView; import com.github.simy4.xpath.view.NodeSetView; import com.github.simy4.xpath.view.NodeView; import com.github.simy4.xpath.view.NumberView; import com.github.simy4.xpath.view.View; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.util.stream.Stream; import static com.github.simy4.xpath.util.TestNode.node; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class LessThanExprTest extends AbstractOperationExprTest { static Stream<View<?>> lesser() { return Stream.of( new LiteralView<>("1.0"), new NumberView<>(1.0), new NodeView<>(node("1.0")), NodeSetView.of(singletonList(node("1.0")), node -> true), BooleanView.of(true) ); } static Stream<View<?>> greater() { return Stream.of( new LiteralView<>("2.0"), new NumberView<>(2.0), new NodeView<>(node("2.0")), NodeSetView.of(singletonList(node("2.0")), node -> true) ); } static Stream<Arguments> lessThan() { return lesser().flatMap(l -> greater().map(g -> arguments(l, g))); } static Stream<Arguments> equals() { return lesser().flatMap(l1 -> lesser().map(l2 -> arguments(l1, l2))); } private static final NodeView<TestNode> parentNode = new NodeView<>(node("node")); @Mock private Navigator<TestNode> navigator; @BeforeEach void setUp() { operationExpr = new LessThanExpr(leftExpr, rightExpr); } @ParameterizedTest(name = "Given views {0} less than {1}") @DisplayName("Should resolve to true") @MethodSource("lessThan") void shouldResolveToTrueWhenLeftIsLessThanRight(View<Node> less, View<Node> greater) { // given when(leftExpr.resolve(any(), any(), anyBoolean())).thenReturn(less); when(rightExpr.resolve(any(), any(), anyBoolean())).thenReturn(greater); // when var result = operationExpr.resolve(navigator, parentNode, false); // then assertThat(result).isEqualTo(BooleanView.of(true)); } @ParameterizedTest(name = "Given views {1} greater than {0}") @DisplayName("Should resolve to false") @MethodSource("lessThan") void shouldResolveToFalseWhenLeftIsGreaterThanRight(View<Node> less, View<Node> greater) { // given when(leftExpr.resolve(any(), any(), anyBoolean())).thenReturn(greater); when(rightExpr.resolve(any(), any(), anyBoolean())).thenReturn(less); // when var result = operationExpr.resolve(navigator, parentNode, false); // then assertThat(result).isEqualTo(BooleanView.of(false)); } @ParameterizedTest(name = "Given views {0} equal to {1}") @DisplayName("Should resolve to false") @MethodSource("equals") void shouldResolveToFalseWhenLeftIsEqualToRight(View<Node> left, View<Node> right) { // given when(leftExpr.resolve(any(), any(), anyBoolean())).thenReturn(left); when(rightExpr.resolve(any(), any(), anyBoolean())).thenReturn(right); // when var result = operationExpr.resolve(navigator, parentNode, false); // then assertThat(result).isEqualTo(BooleanView.of(false)); } @ParameterizedTest(name = "Given views {1} greater than {0} and greedy context") @DisplayName("Should throw") @MethodSource("lessThan") void shouldThrowWhenResolveToFalseAndShouldCreate(View<Node> less, View<Node> greater) { // given when(leftExpr.resolve(any(), any(), anyBoolean())).thenReturn(greater); when(rightExpr.resolve(any(), any(), anyBoolean())).thenReturn(less); // when assertThatThrownBy(() -> operationExpr.resolve(navigator, parentNode, true)) .isInstanceOf(XmlBuilderException.class); } }
SimY4/xpath-to-xml
xpath-to-xml-core/src/test/java/com/github/simy4/xpath/expr/LessThanExprTest.java
Java
apache-2.0
4,863
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; namespace YetiVSI.DebugEngine.Exit { /// <summary> /// Represents the reason for a normal program exit. /// </summary> public enum ExitReason { /// <summary> /// Default value to use in placeholder ExitInfo.Normal values. /// </summary> Unknown, /// <summary> /// Process being debugged has exited by itself. /// </summary> ProcessExited, /// <summary> /// DebugProgram.Terminate() was used to exit the process. /// </summary> DebuggerTerminated, /// <summary> /// Process has detached by itself - perhaps by direct command to LLDB. /// </summary> ProcessDetached, /// <summary> /// DebugProgram.Detach() was used to detach the process. /// </summary> DebuggerDetached, /// <summary> /// Attaching to the process was canceled by the user. /// </summary> AttachCanceled } /// <summary> /// ExitInfo captures relevant information when the debugger exits. /// </summary> public class ExitInfo { public ExitReason ExitReason { get; } public Exception ExitException { get; } ExitInfo(ExitReason exitReason) { ExitReason = exitReason; } ExitInfo(Exception exitException) { ExitException = exitException; } /// <summary> /// Calls |action| with the exception that caused an exit if there is an exception. /// </summary> public void IfError(Action<Exception> action) { if (ExitException != null) { action(ExitException); } } /// <summary> /// Calls |onError| with the exception that caused an exit if there is an exception. /// Otherwise calls |onNormal| with the exit reason. /// </summary> public void HandleResult(Action<ExitReason> onNormal, Action<Exception> onError) { if (ExitException != null) { onError(ExitException); } else { onNormal(ExitReason); } } /// <summary> /// Create an exit info instance representing the "normal" exit case. This is the case when /// the debugger exits without error. /// </summary> public static ExitInfo Normal(ExitReason er) => new ExitInfo(er); /// <summary> /// Create an exit info instance representing exiting in an error case. /// </summary> public static ExitInfo Error(Exception ex) => new ExitInfo(ex); } }
googlestadia/vsi-lldb
YetiVSI/DebugEngine/Exit/ExitInfo.cs
C#
apache-2.0
3,329
'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const ksuid = require('ksuid'); const cloneDeep = require('clone-deep'); const { OADAError } = require('oada-error'); const { default: config } = require('./config'); const requester = require('./requester'); const router = express.Router(); const { users } = require('@oada/lib-arangodb'); function sanitizeDbResult(user) { if (!user) return null; const u = cloneDeep(user); if (u._rev) delete u._rev; if (u.password) delete u.password; return u; } //router.post('/', bodyParser.json({ // strict: false, // type: ['json', '+json'], // limit: '20mb', //})); router.use( bodyParser.json({ strict: false, type: ['json', '+json'], limit: '20mb', }) ); function requestUserWrite(req, id) { // TODO: Sanitize POST body? return requester .send( { connection_id: req.id, domain: req.get('host'), token: req.get('authorization'), authorization: req.authorization, user: req.body, userid: id, // need for PUT, ignored for POST }, config.get('kafka.topics.userRequest') ) .tap(function chkSuccess(resp) { switch (resp.code) { case 'success': return Promise.resolve(); default: let msg = 'write failed with code ' + resp.code; return Promise.reject(new OADAError(msg)); } }); } router.post('/', function (req, res) { req.log.info('Users POST, body = %O', req.body); // Note: if the username already exists, the ksuid() below will end up // silently discarded and replaced in the response with the real one. const newid = ksuid.randomSync().string; // generate a random string for ID // generate an ID for this particular request if (!req.id) req.id = ksuid.randomSync().string; return requestUserWrite(req, newid).then((resp) => { // TODO: Better status code choices? // if db didn't send back a user, it was an update so use id from URL const id = resp && resp.user ? resp.user['_key'] : newid; // return res.redirect(201, req.baseUrl + '/' + id) res.set('content-location', req.baseUrl + '/' + id); return res.status(200).end(); }); }); // Update (merge) a user: router.put('/:id', function (req, res) { req.log.info('Users PUT(id: ' + req.params.id + '), body = %O', req.body); // generate an ID for this particular request if (!req.id) req.id = ksuid.randomSync().string; return requestUserWrite(req, req.params.id).then((resp) => { // TODO: Better status code choices? // if db didn't send back a user, it was an update so use id from URL const id = resp && resp.user ? resp.user['_key'] : req.params.id; // return res.redirect(201, req.baseUrl + '/' + id) res.set('content-location', req.baseUrl + '/' + id); return res.status(200).end(); }); }); // Lookup a username, limited to tokens and users with oada.admin.user scope router.get('/username-index/:uname', function (req, res) { // Check token scope req.log.trace( 'username-index: Checking token scope, req.authorization.scope = %s', req.authorization ? req.authorization.scope : null ); const havetokenscope = req.authorization.scope.find( (s) => s === 'oada.admin.user:read' || s === 'oada.admin.user:all' ); if (!havetokenscope) { req.log.warn( 'WARNING: attempt to lookup user by username (username-index), but token does not have oada.admin.user:read or oada.admin.user:all scope!' ); throw new OADAError( 'Token does not have required oada.admin.user scope', 401 ); } // Check user's scope req.log.trace('username-index: Checking user scope, req.user = %O', req.user); const haveuserscope = Array.isArray(req.user.scope) && req.user.scope.find( (s) => s === 'oada.admin.user:read' || s === 'oada.admin.user:all' ); if (!haveuserscope) { req.log.warn( 'WARNING: attempt to lookup user by username (username-index), but USER does not have oada.admin.user:read or oada.admin.user:all scope!' ); throw new OADAError( 'USER does not have required oada.admin.user scope', 403 ); } return users .findByUsername(req.params.uname) .then((u) => { u = sanitizeDbResult(u); if (!u) { req.log.info( `#username-index: 404: username ${req.params.uname} does not exist` ); res .status(404) .send('Username ' + req.params.uname + ' does not exist.'); return res.end(); } req.log.info( `#username-index: found user, returning info for userid ${u._id}` ); res .set('content-location', `/${u._id}`) .set('content-type', 'application/vnd.oada.user.1+json') .status(200) .json(u); return res.end(); }) .catch((e) => { req.log.error( 'FAILED to find user in DB for username-index, username = ' + req.params.uname + '. Error was: %O', e ); res.status(500).send('Internal Error: ', e.toString()); return res.end(); }); }); router.get('/me', function (req, res, next) { req.url = req.url.replace( /^\/me/, `/${req.user['user_id'].replace(/^users\//, '')}` ); next(); }); //TODO: don't return stuff to anyone anytime router.get('/:id', function (req, res) { return users.findById(req.params.id).then((response) => { // Copy and get rid of password field // eslint-disable-next-line no-unused-vars let user = cloneDeep(response); if (!user) { return res.status(404).end(); } if (user.password) delete user.password; // let { password, ...user } = response // doesn't work if no password comes back res.set('Content-Location', '/users/' + req.params.id); return res.json(user); }); }); module.exports = router;
OADA/oada-srvc-docker
oada/services/http-handler/src/users.js
JavaScript
apache-2.0
5,909
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.security.tools.automation.manager.exception; /** * The class {@code StaticScannerException} extends {@link Exception}, is the general static scanner exception * for all operations dealing with static scanners */ @SuppressWarnings("unused") public class StaticScannerException extends Exception { /** * Constructs a new runtime exception with {@code null} as its * detail message. */ public StaticScannerException() { super(); } /** * Constructs a new runtime exception with the specified detail message. * * @param message Message for the exception */ public StaticScannerException(String message) { super(message); } /** * Constructs a new runtime exception with the specified detail message and * cause. */ public StaticScannerException(String message, Throwable e) { super(message, e); } }
wso2/security-tools
internal/automation-manager/api/src/main/java/org/wso2/security/tools/automation/manager/exception/StaticScannerException.java
Java
apache-2.0
1,590
# Encoding: utf-8 # Cloud Foundry Java Buildpack # Copyright 2013 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'java_buildpack/component/versioned_dependency_component' require 'java_buildpack/container' require 'java_buildpack/container/tomcat/tomcat_utils' module JavaBuildpack module Container # Encapsulates the detect, compile, and release functionality for Tomcat lifecycle support. class TomcatJarSupport < JavaBuildpack::Component::VersionedDependencyComponent include JavaBuildpack::Container # (see JavaBuildpack::Component::BaseComponent#compile) def compile jarname = ["h1.jar", "h2.jar"] puts jarname[0] puts jarname[1] download_jar(jarname[0], tomcat_lib) download_jar(jarname[1], tomcat_lib) #download_jar(jar_name, tomcat_lib) #download_jar(jar_name1, tomcat_lib) end # (see JavaBuildpack::Component::BaseComponent#release) def release end protected # (see JavaBuildpack::Component::VersionedDependencyComponent#supports?) def supports? true end private def jar_name "h1-#{@version}.jar" end def jar_name1 "h2-#{@version}.jar" end end end end
alokhm/java-multi-jar-buildpack
lib/java_buildpack/container/tomcat/tomcat_jar_support.rb
Ruby
apache-2.0
1,813
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/genomics/v1/variants.proto package com.google.genomics.v1; public interface CallSetOrBuilder extends // @@protoc_insertion_point(interface_extends:google.genomics.v1.CallSet) com.google.protobuf.MessageOrBuilder { /** * <pre> * The server-generated call set ID, unique across all call sets. * </pre> * * <code>optional string id = 1;</code> */ java.lang.String getId(); /** * <pre> * The server-generated call set ID, unique across all call sets. * </pre> * * <code>optional string id = 1;</code> */ com.google.protobuf.ByteString getIdBytes(); /** * <pre> * The call set name. * </pre> * * <code>optional string name = 2;</code> */ java.lang.String getName(); /** * <pre> * The call set name. * </pre> * * <code>optional string name = 2;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * <pre> * The sample ID this call set corresponds to. * </pre> * * <code>optional string sample_id = 7;</code> */ java.lang.String getSampleId(); /** * <pre> * The sample ID this call set corresponds to. * </pre> * * <code>optional string sample_id = 7;</code> */ com.google.protobuf.ByteString getSampleIdBytes(); /** * <pre> * The IDs of the variant sets this call set belongs to. This field must * have exactly length one, as a call set belongs to a single variant set. * This field is repeated for compatibility with the * [GA4GH 0.5.1 * API](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/variants.avdl#L76). * </pre> * * <code>repeated string variant_set_ids = 6;</code> */ java.util.List<java.lang.String> getVariantSetIdsList(); /** * <pre> * The IDs of the variant sets this call set belongs to. This field must * have exactly length one, as a call set belongs to a single variant set. * This field is repeated for compatibility with the * [GA4GH 0.5.1 * API](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/variants.avdl#L76). * </pre> * * <code>repeated string variant_set_ids = 6;</code> */ int getVariantSetIdsCount(); /** * <pre> * The IDs of the variant sets this call set belongs to. This field must * have exactly length one, as a call set belongs to a single variant set. * This field is repeated for compatibility with the * [GA4GH 0.5.1 * API](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/variants.avdl#L76). * </pre> * * <code>repeated string variant_set_ids = 6;</code> */ java.lang.String getVariantSetIds(int index); /** * <pre> * The IDs of the variant sets this call set belongs to. This field must * have exactly length one, as a call set belongs to a single variant set. * This field is repeated for compatibility with the * [GA4GH 0.5.1 * API](https://github.com/ga4gh/schemas/blob/v0.5.1/src/main/resources/avro/variants.avdl#L76). * </pre> * * <code>repeated string variant_set_ids = 6;</code> */ com.google.protobuf.ByteString getVariantSetIdsBytes(int index); /** * <pre> * The date this call set was created in milliseconds from the epoch. * </pre> * * <code>optional int64 created = 5;</code> */ long getCreated(); /** * <pre> * A map of additional call set information. This must be of the form * map&lt;string, string[]&gt; (string key mapping to a list of string values). * </pre> * * <code>map&lt;string, .google.protobuf.ListValue&gt; info = 4;</code> */ int getInfoCount(); /** * <pre> * A map of additional call set information. This must be of the form * map&lt;string, string[]&gt; (string key mapping to a list of string values). * </pre> * * <code>map&lt;string, .google.protobuf.ListValue&gt; info = 4;</code> */ boolean containsInfo( java.lang.String key); /** * Use {@link #getInfoMap()} instead. */ @java.lang.Deprecated java.util.Map<java.lang.String, com.google.protobuf.ListValue> getInfo(); /** * <pre> * A map of additional call set information. This must be of the form * map&lt;string, string[]&gt; (string key mapping to a list of string values). * </pre> * * <code>map&lt;string, .google.protobuf.ListValue&gt; info = 4;</code> */ java.util.Map<java.lang.String, com.google.protobuf.ListValue> getInfoMap(); /** * <pre> * A map of additional call set information. This must be of the form * map&lt;string, string[]&gt; (string key mapping to a list of string values). * </pre> * * <code>map&lt;string, .google.protobuf.ListValue&gt; info = 4;</code> */ com.google.protobuf.ListValue getInfoOrDefault( java.lang.String key, com.google.protobuf.ListValue defaultValue); /** * <pre> * A map of additional call set information. This must be of the form * map&lt;string, string[]&gt; (string key mapping to a list of string values). * </pre> * * <code>map&lt;string, .google.protobuf.ListValue&gt; info = 4;</code> */ com.google.protobuf.ListValue getInfoOrThrow( java.lang.String key); }
speedycontrol/googleapis
output/com/google/genomics/v1/CallSetOrBuilder.java
Java
apache-2.0
5,291
package com.wingoku.flatUI; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.PorterDuff; import android.os.Handler; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.EditText; public class WinGokuFlatEditText extends EditText{ String backgroundColor; public WinGokuFlatEditText(Context context) { super(context); initialize(context,null); } public WinGokuFlatEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(context, attrs); } public WinGokuFlatEditText(Context context, AttributeSet attrs) { super(context, attrs); initialize(context, attrs); } private void initialize(Context context, AttributeSet attrs) { if(!isInEditMode()) { this.setBackground(getResources().getDrawable(R.drawable.background)); TypedArray tA = context.obtainStyledAttributes(attrs, R.styleable.wingokuflatui); backgroundColor = tA .getString(R.styleable.wingokuflatui_backgroundColor); tA.recycle(); this.getBackground().setColorFilter(Color.parseColor(backgroundColor), PorterDuff.Mode.DARKEN); } } }
wingoku/WinGoku-Android-FlatUI
src/com/wingoku/flatUI/WinGokuFlatEditText.java
Java
apache-2.0
1,316
/* * Copyright 2014 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.lang.yang; import com.intellij.openapi.fileTypes.LanguageFileType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import com.intellij.lang.yang.icons.YangIcons; public class YangFileType extends LanguageFileType { public static final YangFileType INSTANCE = new YangFileType(); private YangFileType() { super(YangLanguage.INSTANCE); } @NotNull @Override public String getName() { return "Yang file"; } @NotNull @Override public String getDescription() { return "YANG is a data modeling language used to model configuration and\n" + "state data manipulated by the Network Configuration Protocol\n" + "(NETCONF), NETCONF remote procedure calls, and NETCONF notifications.\n"; } @NotNull @Override public String getDefaultExtension() { return "yang"; } @Nullable @Override public Icon getIcon() { return YangIcons.FILE; } }
dave-tucker/intellij-yang
src/main/java/com/intellij/lang/yang/YangFileType.java
Java
apache-2.0
1,655
using System; using Android.Gms.Analytics; using Android.Content; using Newtonsoft.Json.Linq; using System.IO; namespace MonocleGiraffe.Android { public static class AnalyticsHelper { static AnalyticsHelper() { var gaInstace = GoogleAnalytics.GetInstance(AppContext); //gaInstace.SetLocalDispatchPeriod(10); GATracker = gaInstace.NewTracker(GATrackingId); GATracker.EnableAdvertisingIdCollection(true); GATracker.EnableExceptionReporting(true); } private static Context AppContext => global::Android.App.Application.Context; public static Tracker GATracker { get; private set; } private static string gaTrackingId; private static string GATrackingId { get { gaTrackingId = gaTrackingId ?? (string)LoadAnalyticsJson()["google_analytics_property_id"]; return gaTrackingId; } } private static JObject LoadAnalyticsJson() { string content = "{}"; var assets = AppContext.Assets; using (StreamReader sr = new StreamReader(assets.Open("Analytics.json"))) { content = sr.ReadToEnd(); } return JObject.Parse(content); } public static void SendView(string viewName) { GATracker.SetScreenName(viewName); GATracker.Send(new HitBuilders.ScreenViewBuilder().Build()); } public static void SendEvent(string category, string action) { GATracker.Send(new HitBuilders.EventBuilder(category, action).SetLabel("AppEvent").Build()); } public static void SendException(string description, bool isFatal) { GATracker.Send(new HitBuilders.ExceptionBuilder().SetDescription(description).SetFatal(isFatal).Build()); } } }
akshay2000/MonocleGiraffe
MonocleGiraffe/MonocleGiraffe.Android/Helpers/AnalyticsHelper.cs
C#
apache-2.0
1,966
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md for more information * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific * */ package com.khartec.waltz.web.endpoints.api; import com.khartec.waltz.model.database_information.DatabaseInformation; import com.khartec.waltz.model.database_information.DatabaseSummaryStatistics; import com.khartec.waltz.service.database_information.DatabaseInformationService; import com.khartec.waltz.web.DatumRoute; import com.khartec.waltz.web.ListRoute; import com.khartec.waltz.web.endpoints.Endpoint; import com.khartec.waltz.web.json.ApplicationDatabases; import com.khartec.waltz.web.json.ImmutableApplicationDatabases; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.stream.Collectors; import static com.khartec.waltz.web.WebUtilities.*; import static com.khartec.waltz.web.endpoints.EndpointUtilities.*; @Service public class DatabaseInformationEndpoint implements Endpoint { private final DatabaseInformationService databaseInformationService; private static final String BASE_URL = mkPath("api", "database"); @Autowired public DatabaseInformationEndpoint(DatabaseInformationService databaseInformationService) { this.databaseInformationService = databaseInformationService; } @Override public void register() { String findForAppPath = mkPath(BASE_URL, "app", ":id"); String findForAppSelectorPath = mkPath(BASE_URL); String calculateStatsForAppIdSelectorPath = mkPath(BASE_URL, "stats"); ListRoute<DatabaseInformation> findForAppRoute = (request, response) -> databaseInformationService.findByApplicationId(getId(request)); ListRoute<ApplicationDatabases> findForAppSelectorRoute = (request, response) -> databaseInformationService.findByApplicationSelector(readIdSelectionOptionsFromBody(request)) .entrySet() .stream() .map(e -> ImmutableApplicationDatabases.builder() .applicationId(e.getKey()) .databases(e.getValue()) .build()) .collect(Collectors.toList()); DatumRoute<DatabaseSummaryStatistics> calculateStatsForAppIdSelectorRoute = (request, response) -> databaseInformationService.calculateStatsForAppIdSelector(readIdSelectionOptionsFromBody(request)); getForList(findForAppPath, findForAppRoute); postForList(findForAppSelectorPath, findForAppSelectorRoute); postForDatum(calculateStatsForAppIdSelectorPath, calculateStatsForAppIdSelectorRoute); } }
rovats/waltz
waltz-web/src/main/java/com/khartec/waltz/web/endpoints/api/DatabaseInformationEndpoint.java
Java
apache-2.0
3,233
import pytest # Test data # Consider a bunch of Nodes, some of them are parents and some are children. class Node(object): NodeMap = {} def __init__(self, name, parent=None): self.name = name self.children = [] self.NodeMap[self.name] = self if parent: self.parent = self.NodeMap[parent] self.parent.children.append(self) else: self.parent = None def __str__(self): return self.name parents = [ Node("a"), Node("b"), Node("c"), Node("d"), ] childs = [ Node("e", "a"), Node("f", "a"), Node("g", "a"), Node("h", "b"), Node("i", "c"), Node("j", "c"), Node("k", "d"), Node("l", "d"), Node("m", "d"), ] # The test for the parent shall depend on the test of all its children. # Create enriched parameter lists, decorated with the dependency marker. childparam = [ pytest.param(c, marks=pytest.mark.dependency(name="test_child[%s]" % c)) for c in childs ] parentparam = [ pytest.param(p, marks=pytest.mark.dependency( name="test_parent[%s]" % p, depends=["test_child[%s]" % c for c in p.children] )) for p in parents ] @pytest.mark.parametrize("c", childparam) def test_child(c): if c.name == "l": pytest.xfail("deliberate fail") assert False @pytest.mark.parametrize("p", parentparam) def test_parent(p): pass
RKrahl/pytest-dependency
doc/examples/dyn-parametrized.py
Python
apache-2.0
1,397
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisanalyticsv2.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.kinesisanalyticsv2.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteApplicationReferenceDataSourceRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteApplicationReferenceDataSourceRequestProtocolMarshaller implements Marshaller<Request<DeleteApplicationReferenceDataSourceRequest>, DeleteApplicationReferenceDataSourceRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("KinesisAnalytics_20180523.DeleteApplicationReferenceDataSource").serviceName("AmazonKinesisAnalyticsV2").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DeleteApplicationReferenceDataSourceRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DeleteApplicationReferenceDataSourceRequest> marshall(DeleteApplicationReferenceDataSourceRequest deleteApplicationReferenceDataSourceRequest) { if (deleteApplicationReferenceDataSourceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DeleteApplicationReferenceDataSourceRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, deleteApplicationReferenceDataSourceRequest); protocolMarshaller.startMarshalling(); DeleteApplicationReferenceDataSourceRequestMarshaller.getInstance().marshall(deleteApplicationReferenceDataSourceRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
jentfoo/aws-sdk-java
aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/transform/DeleteApplicationReferenceDataSourceRequestProtocolMarshaller.java
Java
apache-2.0
3,041
package in.dream_lab.goffish.giraph.formats; import in.dream_lab.goffish.api.IEdge; import in.dream_lab.goffish.api.IVertex; import in.dream_lab.goffish.giraph.graph.SubgraphId; import in.dream_lab.goffish.giraph.graph.SubgraphVertices; import in.dream_lab.goffish.giraph.graph.DefaultSubgraphEdge; import in.dream_lab.goffish.giraph.graph.DefaultSubgraphVertex; import org.apache.giraph.edge.Edge; import org.apache.giraph.edge.EdgeFactory; import org.apache.giraph.io.formats.AdjacencyListTextVertexInputFormat; import org.apache.giraph.io.formats.TextDoubleDoubleAdjacencyListVertexInputFormat; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.IOException; import java.util.HashMap; /** * Created by anirudh on 30/09/16. */ public class LongDoubleDoubleAdjacencyListSubgraphInputFormat extends AdjacencyListTextSubgraphInputFormat<SubgraphId<LongWritable>, SubgraphVertices, DoubleWritable> { @Override public AdjacencyListTextSubgraphReader createVertexReader(InputSplit split, TaskAttemptContext context) { return new LongDoubleDoubleAdjacencyListSubgraphReader(null); } /** * Vertex reader used with * {@link TextDoubleDoubleAdjacencyListVertexInputFormat} */ protected class LongDoubleDoubleAdjacencyListSubgraphReader extends AdjacencyListTextSubgraphReader { @Override public IEdge<NullWritable, LongWritable, NullWritable> decodeVertexEdge(String id) { LongWritable vertexId = new LongWritable(Long.parseLong(id)); DefaultSubgraphEdge<LongWritable, NullWritable, NullWritable> subgraphEdge = new DefaultSubgraphEdge<>(); subgraphEdge.initialize(NullWritable.get(), NullWritable.get(), vertexId); return subgraphEdge; } @Override public SubgraphVertices getSubgraphVertices() throws IOException, InterruptedException { SubgraphVertices<LongWritable, DoubleWritable, DoubleWritable, LongWritable, LongWritable, LongWritable> subgraphVertices = new SubgraphVertices(); HashMap<LongWritable, IVertex<DoubleWritable, DoubleWritable, LongWritable, LongWritable>> subgraphVerticesMap = new HashMap<>(); while (getRecordReader().nextKeyValue()) { // take all info from each line // Read each vertex Text vertexLine = getRecordReader().getCurrentValue(); String[] processedLine = preprocessLine(vertexLine); IVertex<DoubleWritable, DoubleWritable, LongWritable, LongWritable> subgraphVertex = readVertex(processedLine); subgraphVerticesMap.put(subgraphVertex.getVertexId(), subgraphVertex); } subgraphVertices.initialize(subgraphVerticesMap); subgraphVertices.setSubgraphValue(new LongWritable()); return subgraphVertices; } @Override public Edge<SubgraphId<LongWritable>, DoubleWritable> decodeSubgraphEdge(String value1, String value2) { LongWritable sid = new LongWritable(Long.parseLong(value1)); int pid = Integer.parseInt(value2); SubgraphId<LongWritable> subgraphId = new SubgraphId<>(sid, pid); Edge <SubgraphId<LongWritable>, DoubleWritable> edge = EdgeFactory.create(subgraphId, new DoubleWritable(0)); return edge; } @Override public int decodePId(String s) { return Integer.parseInt(s); } /** * Constructor with * {@link AdjacencyListTextVertexInputFormat.LineSanitizer}. * * @param lineSanitizer the sanitizer to use for reading */ public LongDoubleDoubleAdjacencyListSubgraphReader(AdjacencyListTextSubgraphInputFormat.LineSanitizer lineSanitizer) { super(lineSanitizer); } @Override public LongWritable decodeId(String s) { return new LongWritable(Long.parseLong(s)); } @Override public LongWritable decodeSId(String s) { return new LongWritable(Long.parseLong(s)); } @Override public IVertex readVertex(String[] line) throws IOException{ DefaultSubgraphVertex subgraphVertex = new DefaultSubgraphVertex(); subgraphVertex.initialize(getVId(line), getValue(line), getVertexEdges(line)); return subgraphVertex; } @Override public DoubleWritable decodeValue(String s) { return new DoubleWritable(Double.parseDouble(s)); } @Override public SubgraphId<LongWritable> getSId(String[] line) { SubgraphId<LongWritable> subgraphId = new SubgraphId<LongWritable>(decodeSId(line[0]), decodePId(line[1])); return subgraphId; } } }
KidEinstein/giraph
goffish-giraph/src/main/java/in/dream_lab/goffish/giraph/formats/LongDoubleDoubleAdjacencyListSubgraphInputFormat.java
Java
apache-2.0
5,172
package com.ericharlow.spotlight; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void additionIsCorrect() throws Exception { assertEquals(4, 2 + 2); } }
ericharlow/Spotlight
app/src/test/java/com/ericharlow/spotlight/ExampleUnitTest.java
Java
apache-2.0
316
angular.module('BitGo.API.EnterpriseAPI', []) /* Notes: - This module is for managing all http requests and local caching/state for all Enterprise objects in the app */ .factory('EnterpriseAPI', ['$q', '$location', '$resource', '$rootScope', 'UtilityService', 'CacheService', 'EnterpriseModel', 'NotifyService', function($q, $location, $resource, $rootScope, UtilityService, CacheService, EnterpriseModel, NotifyService) { var DEFAULT_CACHED_ENTERPRISE_ID = 'personal'; var kApiServer = UtilityService.API.apiServer; var PromiseSuccessHelper = UtilityService.API.promiseSuccessHelper; var PromiseErrorHelper = UtilityService.API.promiseErrorHelper; // Cache setup var enterpriseCache = new CacheService.Cache('localStorage', 'Enterprises', 120 * 60 * 1000); /** * update the user's cached current enterprise * @param enterprise {String} id for the new enterprise to set in cache * @private */ function updateUserCurrentEnterpriseCache(enterprise) { var userId = $rootScope.currentUser.settings.id; if (!enterprise || !userId) { throw new Error('missing params'); } enterpriseCache.add('currentEnterprise' + userId, enterprise); } /** * Set up a default current enterprise before a user is set * @private */ function initUserCurrentEnterpriseCache() { var userId = $rootScope.currentUser && $rootScope.currentUser.settings.id; var cachedEnterprise = userId && enterpriseCache.get('currentEnterprise' + userId); if (cachedEnterprise) { // if the user has cached preferences, update the cache based on them return updateUserCurrentEnterpriseCache(cachedEnterprise); } else { // otherwise update the cache with a default current enterprise ('personal') return updateUserCurrentEnterpriseCache(DEFAULT_CACHED_ENTERPRISE_ID); } } /** * Returns the current enterprise * @returns {String} current enterprise id || undefined * @private */ function getCurrentEnterprise() { // If there is no user, return the default cached enterprise var userId = $rootScope.currentUser && $rootScope.currentUser.settings.id; if (!userId) { console.error('Missing current user id'); return; } // Return the user's last cached current enterprise or default to personal var curEnterpriseId = enterpriseCache.get('currentEnterprise' + userId) || 'personal'; return curEnterpriseId; } /** * Sets the new current enterprise object on rootScope * @param enterprise {String} id for the new current enterprise * @private */ function setCurrentEnterprise(enterprise) { if (!enterprise) { throw new Error('Missing enterprise'); } if (_.isEmpty($rootScope.enterprises.all)) { throw new Error('Missing $rootScope.enterprises.all'); } var newCurrentEnterprise = $rootScope.enterprises.all[enterprise.id]; if (!newCurrentEnterprise) { throw new Error('Could not find the enterprise: ' + enterprise.id); } // Set the new current enterprise in the app and cache $rootScope.enterprises.current = newCurrentEnterprise; updateUserCurrentEnterpriseCache($rootScope.enterprises.current.id); // If the new enterprise is different from the one the user is currently in, // broadcast the new event and go to the enterprise's wallets list page if ($rootScope.enterprises.current.id !== UtilityService.Url.getEnterpriseIdFromUrl()) { $rootScope.$emit('EnterpriseAPI.CurrentEnterpriseSet', { enterprises: $rootScope.enterprises }); } } // Fetch all enterprises for the user function getAllEnterprises() { var resource = $resource(kApiServer + '/enterprise', {}); return resource.get({}).$promise .then( function(data) { // Array of enterprises returned var enterprises = data.enterprises; // Reset the rootScope enterprise list $rootScope.enterprises.all = {}; // Create all 'real' enterprise objects _.forEach(enterprises, function(enterpriseData) { enterprise = new EnterpriseModel.Enterprise(enterpriseData); $rootScope.enterprises.all[enterprise.id] = enterprise; enterpriseCache.add(enterprise.name, enterprise); }); // Create the 'personal' enterprise object var personalEnterprise = new EnterpriseModel.Enterprise(); $rootScope.enterprises.all[personalEnterprise.id] = personalEnterprise; enterpriseCache.add(personalEnterprise.name, personalEnterprise); // If an enterprise is set in the url use it; otherwise default to personal var curEnterpriseId = getCurrentEnterprise(); _.forIn($rootScope.enterprises.all, function(enterprise) { if (enterprise.id === curEnterpriseId) { $rootScope.enterprises.current = enterprise; } }); // Let listeners in the app know that the enterprise list was set $rootScope.$emit('EnterpriseAPI.CurrentEnterpriseSet', { enterprises: $rootScope.enterprises }); return enterprises; }, PromiseErrorHelper() ); } /** * Creates an enterprise inquiry for the marketing team * @param inquiry {Object} contains necessary params for the post * @private */ function createInquiry(inquiry) { if (!inquiry) { throw new Error('invalid params'); } var resource = $resource(kApiServer + '/enterprise/inquiry', {}); return new resource.save(inquiry).$promise .then( PromiseSuccessHelper(), PromiseErrorHelper() ); } /** * Sets the users on the current enterprise * @private */ function setCurrentEnterpriseUsers() { if (!$rootScope.enterprises.current) { console.log('Cannot set users on the current enterprise without a current enterprise'); return false; } $rootScope.enterprises.current.setUsers($rootScope.wallets.all); } /** * Decorates each enterprise with wallet data once every wallet returns * @param wallets {Object} collection of BitGo client wallet objects * @private */ function decorateEnterprisesWithWalletShareData(walletShares) { _.forIn($rootScope.enterprises.all, function(enterprise) { enterprise.setWalletShareCount(walletShares); }); } /** * Decorates each enterprise with wallet data once every wallet returns * @param wallets {Object} collection of BitGo client wallet objects * @private */ function decorateEnterprisesWithWalletData(wallets) { _.forIn($rootScope.enterprises.all, function(enterprise) { enterprise.setWalletCount(wallets); enterprise.setBalance(wallets); }); } /** * Returns basic info for an enterprise - used publicly, not scoped to a user * @param { String } enterpriseName * @private * @returns { Promise } */ function getInfoByName(enterprise) { if (!enterprise) { throw new Error('missing enterprise'); } var resource = $resource(kApiServer + '/enterprise/name/' + enterprise, {}); return new resource.get({}).$promise .then( PromiseSuccessHelper(), PromiseErrorHelper() ); } // Event Handling $rootScope.$on('UserAPI.CurrentUserSet', function(evt, user) { initUserCurrentEnterpriseCache(); getAllEnterprises(); }); $rootScope.$on('UserAPI.UserLogoutEvent', function(evt, user) { // clear enterprises on rootscope on logout init(); }); $rootScope.$on('WalletsAPI.UserWalletsSet', function(evt, data) { if (_.isEmpty(data.allWallets)) { return; } // Set users on the current enterprise setCurrentEnterpriseUsers(); // Decorate all enterprises with the latest wallet data decorateEnterprisesWithWalletData(data.allWallets); }); $rootScope.$on('WalletSharesAPI.AllUserWalletSharesSet', function(evt, data) { if (_.isEmpty(data.walletShares.incoming) && _.isEmpty(data.walletShares.outgoing)) { return; } // Decorate all enterprises with the latest walletShares data decorateEnterprisesWithWalletShareData(data.walletShares); }); function init() { $rootScope.enterprises = { all: {}, current: null }; } init(); // In-client API return { getInfoByName: getInfoByName, getAllEnterprises: getAllEnterprises, setCurrentEnterprise: setCurrentEnterprise, getCurrentEnterprise: getCurrentEnterprise, createInquiry: createInquiry }; } ]);
jmaurice/bitgo-chrome
api/scripts/enterpriseAPI.js
JavaScript
apache-2.0
8,868
package tracker.start; /** * Class Input класс интерфейс для унификации ввода. * @author Zaur Turabayev * @since 04.01.2016 * @version 1 */ public interface Input { String ask(String question); int ask(String question, int[] range); }
smileztv/my_learning
chapter_002/src/main/java/tracker/start/Input.java
Java
apache-2.0
282
/* * StreamReader.java January 2010 * * Copyright (C) 2010, Niall Gallagher <niallg@users.sf.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.simpleframework.xml.stream; import java.util.Iterator; import extra.javax.xml.stream.Location; import extra.javax.xml.stream.XMLEventReader; import extra.javax.xml.stream.events.Attribute; import extra.javax.xml.stream.events.Characters; import extra.javax.xml.stream.events.StartElement; import extra.javax.xml.stream.events.XMLEvent; /** * The <code>StreamReader</code> object provides an implementation * for reading XML events using StAX. This will pretty much wrap * core StAX events as the framework is very closely related. The * implementation is basically required to ensure StAX events can * be digested by the core reader. For performance this will match * the underlying implementation closely as all this basically * does is act as a means to adapt the underlying framework events. * * @author Niall Gallagher * * @see org.simpleframework.xml.stream.StreamProvider */ class StreamReader implements EventReader { /** * This is the reader that is used to parse the XML document. */ private XMLEventReader reader; /** * This is used to keep track of any events that were peeked. */ private EventNode peek; /** * Constructor for the <code>StreamReader</code> object. This * creates a reader that extracts events from the provided object. * All StAX events returned from the provided instance will be * adapted so that they can be digested by the core reader. * * @param reader this is the reader used to parse the XML source */ public StreamReader(XMLEventReader reader) { this.reader = reader; } /** * This is used to peek at the node from the document. This will * scan through the document, ignoring any comments to find the * next relevant XML event to acquire. Typically events will be * the start and end of an element, as well as any text nodes. * * @return this returns the next event taken from the document */ public EventNode peek() throws Exception { if(peek == null) { peek = next(); } return peek; } /** * This is used to take the next node from the document. This will * scan through the document, ignoring any comments to find the * next relevant XML event to acquire. Typically events will be * the start and end of an element, as well as any text nodes. * * @return this returns the next event taken from the source XML */ public EventNode next() throws Exception { EventNode next = peek; if(next == null) { next = read(); } else { peek = null; } return next; } /** * This is used to read the next node from the document. This will * scan through the document, ignoring any comments to find the * next relevant XML event to acquire. Typically events will be * the start and end of an element, as well as any text nodes. * * @return this returns the next event taken from the document */ private EventNode read() throws Exception { XMLEvent event = reader.nextEvent(); if(!event.isEndDocument()) { if(event.isStartElement()) { return start(event); } if(event.isCharacters()) { return text(event); } if(event.isEndElement()) { return end(); } return read(); } return null; } /** * This is used to convert the provided event to a start event. The * conversion process ensures the node can be digested by the core * reader and used to provide an <code>InputNode</code> that can * be used to represent an XML elements within the source document. * * @param event the event that is to be converted to a start event * * @return this returns a start event created from the given event */ private Start start(XMLEvent event) { Start node = new Start(event); if(node.isEmpty()) { return build(node); } return node; } /** * This is used to build the attributes that are to be used to * populate the start event. Populating the start event with the * attributes it contains is required so that each element will * contain its associated attributes. Only attributes that are * not reserved will be added to the start event. * * @param event this is the start event that is to be populated * * @return this returns a start event with its attributes */ private Start build(Start event) { Iterator<Attribute> list = event.getAttributes(); while (list.hasNext()) { Attribute node = list.next(); Entry entry = attribute(node); if(!entry.isReserved()) { event.add(entry); } } return event; } /** * This is used to convert the provided object to an attribute. The * conversion process ensures the node can be digested by the core * reader and used to provide an <code>InputNode</code> that can * be used to represent an XML attribute within the source document. * * @param entry the object that is to be converted to an attribute * * @return this returns an attribute created from the given object */ private Entry attribute(Attribute entry) { return new Entry(entry); } /** * This is used to convert the provided event to a text event. The * conversion process ensures the node can be digested by the core * reader and used to provide an <code>InputNode</code> that can * be used to represent an XML attribute within the source document. * * @param event the event that is to be converted to a text event * * @return this returns the text event created from the given event */ private Text text(XMLEvent event) { return new Text(event); } /** * This is used to create an event to signify that an element has * just ended. End events are important as they allow the core * reader to determine if a node is still in context. This provides * a more convenient way to use <code>InputNode</code> objects as * they should only ever be able to extract their children. * * @return this returns an end event to signify an element close */ private End end() { return new End(); } /** * The <code>Entry</code> object is used to represent an attribute * within a start element. This holds the name and value of the * attribute as well as the namespace prefix and reference. These * details can be used to represent the attribute so that should * the core reader require these details they can be acquired. * * @author Niall Gallagher */ private static class Entry extends EventAttribute { /** * This is the attribute object representing this attribute. */ private final Attribute entry; /** * Constructor for the <code>Entry</code> object. This creates * an attribute object that is used to extract the name, value * namespace prefix, and namespace reference from the provided * node. This is used to populate any start events created. * * @param entry this is the node that represents the attribute */ public Entry(Attribute entry) { this.entry = entry; } /** * This provides the name of the attribute. This will be the * name of the XML attribute without any namespace prefix. If * the name begins with "xml" then this attribute is reserved. * according to the namespaces for XML 1.0 specification. * * @return this returns the name of this attribute object */ public String getName() { return entry.getName().getLocalPart(); } /** * This is used to acquire the namespace prefix associated with * this attribute. A prefix is used to qualify the attribute * within a namespace. So, if this has a prefix then it should * have a reference associated with it. * * @return this returns the namespace prefix for the attribute */ public String getPrefix() { return entry.getName().getPrefix(); } /** * This is used to acquire the namespace reference that this * attribute is in. A namespace is normally associated with an * attribute if that attribute is prefixed with a known token. * If there is no prefix then this will return null. * * @return this provides the associated namespace reference */ public String getReference() { return entry.getName().getNamespaceURI(); } /** * This returns the value of the event. This will be the value * that the attribute contains. If the attribute does not have * a value then this returns null or an empty string. * * @return this returns the value represented by this object */ public String getValue() { return entry.getValue(); } /** * This returns true if the attribute is reserved. An attribute * is considered reserved if it begins with "xml" according to * the namespaces in XML 1.0 specification. Such attributes are * used for namespaces and other such details. * * @return this returns true if the attribute is reserved */ public boolean isReserved() { return false; } /** * This is used to return the node for the attribute. Because * this represents a StAX attribute the StAX object is returned. * Returning the node helps with certain debugging issues. * * @return this will return the source object for this */ public Object getSource() { return entry; } } /** * The <code>Start</code> object is used to represent the start of * an XML element. This will hold the attributes associated with * the element and will provide the name, the namespace reference * and the namespace prefix. For debugging purposes the source XML * element is provided for this start event. * * @author Niall Gallagher */ private static class Start extends EventElement { /** * This is the start element to be used by this start event. */ private final StartElement element; /** * This is the element location used to detmine line numbers. */ private final Location location; /** * Constructor for the <code>Start</code> object. This will * wrap the provided node and expose the required details such * as the name, namespace prefix and namespace reference. The * provided element node can be acquired for debugging purposes. * * @param event this is the element being wrapped by this */ public Start(XMLEvent event) { this.element = event.asStartElement(); this.location = event.getLocation(); } /** * This is used to provide the line number the XML event was * encountered at within the XML document. If there is no line * number available for the node then this will return a -1. * * @return this returns the line number if it is available */ public int getLine() { return location.getLineNumber(); } /** * This provides the name of the event. This will be the name * of an XML element the event represents. If there is a prefix * associated with the element, this extracts that prefix. * * @return this returns the name without the namespace prefix */ public String getName() { return element.getName().getLocalPart(); } /** * This is used to acquire the namespace prefix associated with * this node. A prefix is used to qualify an XML element or * attribute within a namespace. So, if this represents a text * event then a namespace prefix is not required. * * @return this returns the namespace prefix for this event */ public String getPrefix() { return element.getName().getPrefix(); } /** * This is used to acquire the namespace reference that this * node is in. A namespace is normally associated with an XML * element or attribute, so text events and element close events * are not required to contain any namespace references. * * @return this will provide the associated namespace reference */ public String getReference() { return element.getName().getNamespaceURI(); } /** * This is used to acquire the attributes associated with the * element. Providing the attributes in this format allows * the reader to build a list of attributes for the event. * * @return this returns the attributes associated with this */ public Iterator<Attribute> getAttributes() { return element.getAttributes(); } /** * This is used to return the node for the element. Because * this represents a StAX event the StAX event is returned. * Returning the node helps with certain debugging issues. * * @return this will return the source object for this */ public Object getSource() { return element; } } /** * The <code>Text</code> object is used to represent a text event. * If wraps a node that holds text consumed from the document. * These are used by <code>InputNode</code> objects to extract the * text values for elements For debugging this exposes the node. * * @author Niall Gallagher */ private static class Text extends EventToken { /** * This is the event that is used to represent the text value. */ private final Characters text; /** * Constructor for the <code>Text</code> object. This creates * an event that provides text to the core reader. Text can be * in the form of a CDATA section or a normal text entry. * * @param event this is the node that represents the text value */ public Text(XMLEvent event) { this.text = event.asCharacters(); } /** * This is true as this event represents a text token. Text * tokens are required to provide a value only. So namespace * details and the node name will always return null. * * @return this returns true as this event represents text */ public boolean isText() { return true; } /** * This returns the value of the event. This will return the * text value contained within the node. If there is no * text within the node this should return an empty string. * * @return this returns the value represented by this event */ public String getValue() { return text.getData(); } /** * This is used to return the node for the text. Because * this represents a StAX event the StAX event is returned. * Returning the node helps with certain debugging issues. * * @return this will return the source object for this */ public Object getSource() { return text; } } /** * The <code>End</code> object is used to represent the end of an * element. It is used by the core reader to determine which nodes * are in context and which ones are out of context. This allows * the input nodes to determine if it can read any more children. * * @author Niall Gallagher */ private static class End extends EventToken { /** * This is true as this event represents an element end. Such * events are required by the core reader to determine if a * node is still in context. This helps to determine if there * are any more children to be read from a specific node. * * @return this returns true as this token represents an end */ public boolean isEnd() { return true; } } }
sn00py2/SimpleXMLLegacy
src/org/simpleframework/xml/stream/StreamReader.java
Java
apache-2.0
17,189
# -*- coding:utf-8 -*- from application import app if __name__ == '__main__': app.run(host='0.0.0.0', port=8000, debug=True)
oceanio/flask-boot
server.py
Python
apache-2.0
130
/* * #%L * Wisdom-Framework * %% * Copyright (C) 2013 - 2014 Wisdom Framework * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.wisdom.wamp; import java.util.*; /** * Represents a client accessing the server using WAMP. * <p/> * This class manages the topics listened by the clients and its URL-CURL relations (prefix). */ public class WampClient { private final String id; private final Set<String> topics; private final Map<String, String> prefixes; private final String wisdomClientId; public WampClient(String wisdomClientId) { this.topics = new HashSet<>(); this.prefixes = new HashMap<>(); this.wisdomClientId = wisdomClientId; this.id = UUID.randomUUID().toString(); } public synchronized void subscribe(String topic) { topics.add(getUri(topic)); } public synchronized boolean isSubscribed(String topic) { return topics.contains(getUri(topic)); } public synchronized void unsubscribe(String topic) { topics.remove(getUri(topic)); } public String session() { return this.id; } public String wisdomClientId() { return this.wisdomClientId; } public void registerPrefix(String prefix, String uri) { prefixes.put(prefix, uri); } public String getUri(String uri) { int index = uri.indexOf(":"); // Detect if the given uri is prefixed. if (index != -1 && !uri.startsWith("http")) { String prefix = uri.substring(0, index); String tail = uri.substring(index + 1); String url = prefixes.get(prefix); if (url != null) { return url + tail; } } return uri; } }
wisdom-framework/wisdom-wamp
src/main/java/org/wisdom/wamp/WampClient.java
Java
apache-2.0
2,288
export const ChampionMastery = new Mongo.Collection('championMastery'); import {updateChampionMasteries} from '../riot/championMastery'; import {Champions} from './champion'; import {Summoners} from './summoner'; import {Regions} from './region.js'; ChampionMastery.helpers({ champion: function(){ return Champions.findOne({id:this.data.championId}); }, summoner:function(){ return Summoners.findOne({id:this.data.playerId}) } }); if (Meteor.isServer) { var Future = Npm.require('fibers/future'); // This code only runs on the server Meteor.publish('SummonerChampionMastery', function (region, summonerId) { check(region, String); check(summonerId, Number); let masteries = ChampionMastery.find({ "data.playerId": summonerId, region: region }); if(masteries.count() == 0){ var regionObject = Regions.findOne({slug:region}); updateChampionMasteries(regionObject,summonerId); } return masteries; }); Meteor.publish('ChampionLeaderBoards', function (regions, championId, size, offset) { check(regions, Array); check(championId, Number); check(size, Number); check(offset, Number); let championMasteries = ChampionMastery.find({ "data.championId": championId, region: {$in: regions} }, { sort: {"data.championPoints": -1}, limit: size, skip: size * offset }); var ids = championMasteries.map(function(championMastery){ return championMastery.data.playerId; }); let users = Summoners.find({ id: {$in: ids} }); return [ championMasteries, users ] }); Meteor.publish("leaderBoardsCount", function (regions, championId) { check(regions, Array); check(championId, Number); let subscription = this; let summonerCount = ChampionMastery.find({ "data.championId": championId, region: {$in: regions} }).count(); let countObject = {}; countObject.summonerCount = summonerCount; countObject.type = 'leaderboard'; // should be added because all your counts will be contained in one collection subscription.added('counts', Random.id(), countObject); subscription.ready(); }); } Meteor.methods({ 'updateSummonerStats'(regionSlug, summonerId) { check(regionSlug, String); check(summonerId, String); if(Meteor.isServer){ let region = Regions.findOne({slug:regionSlug}); updateChampionMasteries(region,summonerId); } }, 'getLeaderBoardPosition'(championId, regionSlug, summonerId){ check(regionSlug, String); check(summonerId, Number); check(championId, Number); if(Meteor.isServer){ var future = new Future(); let championMasteries = ChampionMastery.find({ "data.championId": championId, region: regionSlug },{sort: {"data.championPoints": -1}}); championMasteries.forEach(function(mastery, index){ if(mastery.region === regionSlug && mastery.data.playerId == summonerId){ future.return(index); } }); return future.wait(); } }, 'refreshMasteries'(region, summonerId){ check(region, String); check(summonerId, Number); let regionObject = Regions.findOne({slug:region}); let summoner = Summoners.findOne({ id: summonerId, region: region }); if(!summoner.hasOwnProperty('statsRefreshedAt')){ summoner.statsRefreshedAt = new Date(); Summoners.update(summoner._id, summoner); updateChampionMasteries(regionObject,summonerId); }else { var minutes = moment(new Date()).diff(moment(summoner.statsRefreshedAt), 'minutes'); if(minutes > 60){ summoner.statsRefreshedAt = new Date(); Summoners.update(summoner._id, summoner); updateChampionMasteries(regionObject,summonerId); } } } });
Dragonpurse/mastery-lb
imports/api/championMastery.js
JavaScript
apache-2.0
4,333