lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
42b1ddbc5d898a8948c8be0c324ca99b7126c08e
0
antsouchlos/MUN_Platform_Web,antsouchlos/MUN_Platform_Web,antsouchlos/MUN_Platform_Web,antsouchlos/MUN_Platform_Web,antsouchlos/MUN_Platform_Web
//takes the the text of a select-option as an argument and returns only the relevant part for download (only the resolution name and topic - without the id) function getRelevant(itemValue) { var result = ""; var writing = false; for (i = 0; i < itemValue.length; i++) { if (!writing) { if (itemValue.charAt(i) == ':') { i++; writing = true; } } else { result += itemValue.charAt(i); } } return result; } //extract just the committee of a string of the form: "[committee]/[topic]/[name]" function getCommittee(txt) { var result= ""; for (i = 0; i < txt.length; i++) { if (txt.charAt(i) == '/') break; result += txt.charAt(i); } return result; } //extract just the name of a string of the form: "[committee]/[topic]/[name]" function getName(txt) { var result= ""; var writing = 0; for (i = 0; i < txt.length; i++) { if (writing < 2) { if (txt.charAt(i) == '/') writing++; } else { result += txt.charAt(i); } } return result; } //extract just the topic of a string of the form: "[committee]/[topic]/[name]" function getTopic(txt) { var result= ""; var writing = false; for (i = 0; i < txt.length; i++) { if (!writing) { if (txt.charAt(i) == '/') writing = true; } else { if (txt.charAt(i) == '/') break; result += txt.charAt(i); } } return result; } function download() { var list = document.getElementById("resList"); //make sure something is selected if (list.selectedIndex != -1) { //get selected list item var selectedItem = list.options[list.selectedIndex].text; //get just the resolution's name and topic from the text of the item var relevant = getRelevant(selectedItem); var committee = getCommittee(relevant); var resName = getName(relevant); var resTopic = getTopic(relevant); //set up the firebase reference var storageRef = firebase.storage().ref(); //download file storageRef.child("resolutions").child(committee).child(resTopic).child(resName).getDownloadURL().then(function(url) { document.location.href = url; }).catch(function(error) { alert("An error occurred while downloading file"); }); } else { alert("You must choose a resolution to download"); } } //takes the value of a select-option (form: "Resolution [id]: [topic]/[name]") as an argument and returns the id function getId(txt) { var result = ""; var writing = false; for (i = 0; i < txt.length; i++) { if (!writing) { if (txt.charAt(i) == ' ') writing = true; } else { if (txt.charAt(i) == ':') break; else result += txt.charAt(i); } } return parseInt(result); } //an array containing a copy of the resolutions' ids of "resList" var resList_ids = []; function getInsertionIndex(id) { var resList = document.getElementById("resList"); var array = []; for (i = 0 ; i < resList_ids.length; i++) { if (resList_ids[i] == id-1) return (i +1); if (id < resList_ids[i]) array.push(resList_ids[i]); } if (array.length == 0) return resList_ids.length; var smallest = id; for (i = 0; i < array.length; i++) { if (array[i] < smallest) smallest = array[i]; } return (resList_ids.indexOf(smallest) -1); } function addChild(name, id) { var list = document.getElementById("resList"); var item = document.createElement("option"); item.text = "Resolution " + id + ": " + name; list.add(item); resList_ids.splice(getInsertionIndex(id), 0, id); list.add(item, getInsertionIndex(id)); } function changeChild(name, index) { var list = document.getElementById("resList"); var item = document.createElement("option"); item.text = "Resolution " + (index+1) + ": " + name; list.remove(index); list.add(item, index); } function removeChild(index) { var list = document.getElementById("resList"); list.remove(index); } //listen for changes to the children of "reference" and update "resList" accordingly function listen(reference, topic, committee) { //add an item to list when a child is added to the database reference.on('child_added', function(childSnapshot, prevChildKey) { if (prevChildKey == null) prevChildKey = "0"; addChild(committee + '/' + topic + '/' + childSnapshot.val(), parseInt(childSnapshot.key)); }); //change an item's text when the value of the corresponding child is changed in the database reference.on('child_changed', function(childSnapshot, prevChildKey) { if (prevChildKey == null) prevChildKey = "0"; changeChild(committee + '/' + topic + '/' + childSnapshot.val(), parseInt(childSnapshot.key)-1); }); //remove an item when the corresponding child is removed from the database reference.on('child_removed', function(oldChildSnapshot) { removeChild(parseInt(oldChildSnapshot.key-1)); }); } function init() { //add listener to the logout button document.getElementById("logout_link").onclick = function () { firebase.auth().signOut(); document.location.href = "index.html"; //make sure the default link behaviour isn't followed return false; }; //add listener to the "download" button var download_link = document.getElementById("download_link"); download_link.onclick = function() { download(); return false; } var committee_array = ["environmental", "humanitarian", "political", "disarmament"]; const resolutionRef = firebase.database().ref().child('resolutions'); for (i = 0; i < 4; i++) { var committeeRef = resolutionRef.child(committee_array[i]); listen(committeeRef.child("topic 1"), "topic 1", committee_array[i]); listen(committeeRef.child("topic 2"), "topic 2", committee_array[i]); listen(committeeRef.child("topic 3"), "topic 3", committee_array[i]); listen(committeeRef.child("topic 4"), "topic 4", committee_array[i]); } } window.onload = init;
public/assets/js/site_specific/staff.js
//takes the the text of a select-option as an argument and returns only the relevant part for download (only the resolution name and topic - without the id) function getRelevant(itemValue) { var result = ""; var writing = false; for (i = 0; i < itemValue.length; i++) { if (!writing) { if (itemValue.charAt(i) == ':') { i++; writing = true; } } else { result += itemValue.charAt(i); } } return result; } //extract just the committee of a string of the form: "[committee]/[topic]/[name]" function getCommittee(txt) { var result= ""; for (i = 0; i < txt.length; i++) { if (txt.charAt(i) == '/') break; result += txt.charAt(i); } return result; } //extract just the name of a string of the form: "[committee]/[topic]/[name]" function getName(txt) { var result= ""; var writing = 0; for (i = 0; i < txt.length; i++) { if (writing < 2) { if (txt.charAt(i) == '/') writing++; } else { result += txt.charAt(i); } } return result; } //extract just the topic of a string of the form: "[committee]/[topic]/[name]" function getTopic(txt) { var result= ""; var writing = false; for (i = 0; i < txt.length; i++) { if (!writing) { if (txt.charAt(i) == '/') writing = true; } else { if (txt.charAt(i) == '/') break; result += txt.charAt(i); } } return result; } function download() { var list = document.getElementById("resList"); //make sure something is selected if (list.selectedIndex != -1) { //get selected list item var selectedItem = list.options[list.selectedIndex].text; //get just the resolution's name and topic from the text of the item var relevant = getRelevant(selectedItem); var committee = getCommittee(relevant); var resName = getName(relevant); var resTopic = getTopic(relevant); alert(committee); alert(resName); alert(resTopic); //set up the firebase reference var storageRef = firebase.storage().ref(); //download file storageRef.child("resolutions").child(committee).child(resTopic).child(resName).getDownloadURL().then(function(url) { document.location.href = url; }).catch(function(error) { alert("An error occurred while downloading file"); }); } else { alert("You must choose a resolution to download"); } } //takes the value of a select-option (form: "Resolution [id]: [topic]/[name]") as an argument and returns the id function getId(txt) { var result = ""; var writing = false; for (i = 0; i < txt.length; i++) { if (!writing) { if (txt.charAt(i) == ' ') writing = true; } else { if (txt.charAt(i) == ':') break; else result += txt.charAt(i); } } return parseInt(result); } //an array containing a copy of the resolutions' ids of "resList" var resList_ids = []; function getInsertionIndex(id) { var resList = document.getElementById("resList"); var array = []; for (i = 0 ; i < resList_ids.length; i++) { if (resList_ids[i] == id-1) return (i +1); if (id < resList_ids[i]) array.push(resList_ids[i]); } if (array.length == 0) return resList_ids.length; var smallest = id; for (i = 0; i < array.length; i++) { if (array[i] < smallest) smallest = array[i]; } return (resList_ids.indexOf(smallest) -1); } function addChild(name, id) { var list = document.getElementById("resList"); var item = document.createElement("option"); item.text = "Resolution " + id + ": " + name; list.add(item); resList_ids.splice(getInsertionIndex(id), 0, id); list.add(item, getInsertionIndex(id)); } function changeChild(name, index) { var list = document.getElementById("resList"); var item = document.createElement("option"); item.text = "Resolution " + (index+1) + ": " + name; list.remove(index); list.add(item, index); } function removeChild(index) { var list = document.getElementById("resList"); list.remove(index); } //listen for changes to the children of "reference" and update "resList" accordingly function listen(reference, topic, committee) { //add an item to list when a child is added to the database reference.on('child_added', function(childSnapshot, prevChildKey) { if (prevChildKey == null) prevChildKey = "0"; addChild(committee + '/' + topic + '/' + childSnapshot.val(), parseInt(childSnapshot.key)); }); //change an item's text when the value of the corresponding child is changed in the database reference.on('child_changed', function(childSnapshot, prevChildKey) { if (prevChildKey == null) prevChildKey = "0"; changeChild(committee + '/' + topic + '/' + childSnapshot.val(), parseInt(childSnapshot.key)-1); }); //remove an item when the corresponding child is removed from the database reference.on('child_removed', function(oldChildSnapshot) { removeChild(parseInt(oldChildSnapshot.key-1)); }); } function init() { //add listener to the logout button document.getElementById("logout_link").onclick = function () { firebase.auth().signOut(); document.location.href = "index.html"; //make sure the default link behaviour isn't followed return false; }; //add listener to the "download" button var download_link = document.getElementById("download_link"); download_link.onclick = function() { download(); return false; } var committee_array = ["environmental", "humanitarian", "political", "disarmament"]; const resolutionRef = firebase.database().ref().child('resolutions'); for (i = 0; i < 4; i++) { var committeeRef = resolutionRef.child(committee_array[i]); listen(committeeRef.child("topic 1"), "topic 1", committee_array[i]); listen(committeeRef.child("topic 2"), "topic 2", committee_array[i]); listen(committeeRef.child("topic 3"), "topic 3", committee_array[i]); listen(committeeRef.child("topic 4"), "topic 4", committee_array[i]); } } window.onload = init;
removed debug messaged
public/assets/js/site_specific/staff.js
removed debug messaged
<ide><path>ublic/assets/js/site_specific/staff.js <ide> var committee = getCommittee(relevant); <ide> var resName = getName(relevant); <ide> var resTopic = getTopic(relevant); <del> <del> alert(committee); <del> alert(resName); <del> alert(resTopic); <ide> <ide> //set up the firebase reference <ide> var storageRef = firebase.storage().ref();
JavaScript
mit
14dcfb10d971e69539e91bba9371ae0f482eed8c
0
CoursesPlus/CoursesPlus,CoursesPlus/CoursesPlus
var disabledComponentList = []; function saveChanges() { cpal.storage.setKey("disabledComponents", disabledComponentList, function() { console.log("Saved changes!"); }); } function createList(sortedComponents, $ulToAppendTo, checkList, checkPresence, clickEvent) { //var sortedComponents = window.components; for (var componentIndex in sortedComponents) { if (componentIndex == "runAll") { continue; } var component = sortedComponents[componentIndex]; var $appendMeReally = $('<li class="col-1-4 feature"></li>'); $appendMeReally.attr("data-componentIndex", componentIndex); var $appendMe = $('<div class="content"></div>'); $appendMe.addClass("feature"); var $check = $("<input type=\"checkbox\" />"); $check.addClass("featureCheck"); $check.prop("checked", (checkPresence ? checkList.indexOf(componentIndex) != -1 : checkList.indexOf(componentIndex) == -1)); $check.attr("data-index", componentIndex); $check.click(clickEvent); $appendMe.append($check); var $label = $("<strong></strong>"); $label.addClass("featureLabel"); $label.html(/*"&nbsp;" + */component.displayName); $appendMe.append($label); var $desc = $("<p></p>"); $desc.addClass("featureDesc"); $desc.html(component.description); $appendMe.append($("<br />")); $appendMe.append($desc); var $req = $("<p></p>"); $req.addClass("featureReq"); if (component.requires.length > 0) { var result = "This feature requires "; $.each(component.requires, function(index) { if (index != 0) { result += ","; } if (component.requires.length > 1 && index == (component.requires.length - 1)) { result += " and "; } firstOne = false; result += components[this].displayName; }); result += " to be enabled."; $req.html(result); $appendMe.append($req); } $appendMeReally.append($appendMe) $ulToAppendTo.append($appendMeReally); } } function progressHandlingFunction(e) { console.log(e); if(e.lengthComputable){ //$('progress').attr({value:e.loaded,max:e.total}); } } function saveBgUrlSizing(url) { cpal.storage.setKey("backgroundImage", { url: url, sizing: $(".bgSizing:checked").val() }); } function saveBgSizing() { if ($("#backgroundImagePreview").attr("src") != "images/nobg.png") { saveBgUrlSizing($("#backgroundImagePreview").attr("src")); } } function showLoading() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").hide(); $("#uploadingText").show(); } function hideLoading() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").show(); $("#uploadingText").hide(); } function hideConnecting() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").show(); $("#connectingText").hide(); } function uploadImageAndSetBg() { if ($("#fileToUpload").val() == "") { alert("Please select an image with the Choose File button! (above the green Upload Image button)"); return false; } showLoading(); var formData = new FormData($('form')[0]); $.ajax({ url: 'https://coursesplus.tk/usrupl/uploadFilePost.php', //Server script to process data type: 'POST', data: formData, cache: false, dataType: 'json', xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, //Ajax events //beforeSend: beforeSendHandler, success: function(res) { if (res.error) { alert("Error uploading image - " + res.errorMsg); hideLoading(); window.location.reload(); return; } $("#backgroundImagePreview").attr("src", res.url); hideLoading(); saveBgSizing(); console.log("Image uploaded to " + res.url + "!"); }, error: function(jqXHR, textStatus, errorThrown) { hideLoading(); alert("Unknown error uploading image!"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); window.location.reload(); }, // Options to tell jQuery not to process data or worry about content-type. contentType: false, processData: false }); return false; } var onBgColorPickerChange = function() { var newColor = $("#secretColorPicker").val(); $(".background.custom").css("background-color", newColor); $(".background.custom").css("color", newColor); cpal.storage.setKey("backgroundColor", newColor); }; var onTextColorPickerChange = function() { var newColor = $("#secretTextColorPicker").val(); $(".textColor.custom").css("background-color", newColor); $(".textColor.custom").css("color", newColor); cpal.storage.setKey("textColor", newColor); }; var onLinkTextColorPickerChange = function() { var newColor = $("#secretLinkTextColorPicker").val(); $(".linkTextColor.custom").css("background-color", newColor); $(".linkTextColor.custom").css("color", newColor); cpal.storage.setKey("linkTextColor", newColor); }; var onNavTextColorPickerChange = function() { var newColor = $("#secretNavTextColorPicker").val(); $(".navTextColor.custom").css("background-color", newColor); $(".navTextColor.custom").css("color", newColor); cpal.storage.setKey("navTextColor", newColor); }; function handleServicePart2(index, thisService) { console.log("All permissions done!"); cpal.storage.getKey("services", function(result) { serviceList = ($.isArray(result) ? result : []); console.log(serviceList); serviceList.push(index); cpal.storage.setKey("services", serviceList, function() { thisService.onEnable(); }); }); } $(document).ready(function() { cpal.storage.getKey("services", function(result) { var serviceList = ($.isArray(result) ? result : []); createList(window.services, $("#services > ul"), serviceList, true, function() { var index = $(this).attr("data-index"); var $this = $(this); var thisService = window.services[index]; if ($(this).prop("checked")) { if (thisService.origins != []) { // TODO: cpal // Do we have them? console.log("Asking for permissions..."); chrome.permissions.contains({ permissions: [], origins: thisService.origins }, function(result) { if (result) { // Done with permission stuff! handleServicePart2(index, thisService); } else { // OK, let's ask. chrome.permissions.request({ permissions: [], origins: thisService.origins }, function(granted) { if (granted) { // YAAAY handleServicePart2(index, thisService); } else { $this.prop("checked", false); alert(thisService.displayName + " requires those permissions."); } }); } }); } else { handleServicePart2(index, thisService); } } else { var componentIndex = $(this).attr("data-index"); cpal.storage.getKey("services", function(result) { serviceList = ($.isArray(result) ? result : []); console.log(componentIndex); serviceList.splice(serviceList.indexOf(componentIndex), 1); cpal.storage.setKey("services", serviceList, function() { }); }); thisService.onDisable(); } }); }); cpal.storage.getKey("disabledComponents", function(result) { disabledComponentList = ($.isArray(result) ? result : []); console.log(disabledComponentList); createList(window.components, $("#features > ul"), disabledComponentList, false, function() { var sortedComponents = window.components; var index = $(this).attr("data-index"); var featureList = []; for (var checkInd in sortedComponents) { if (checkInd == "createErrorModal" || checkInd == "runAll") { continue; } if (sortedComponents[checkInd].requires.indexOf(index) != -1) { featureList.push(sortedComponents[checkInd].displayName); } } if ($(this).prop("checked")) { disabledComponentList.splice(disabledComponentList.indexOf(index), 1); } else { if (featureList.length > 0) { var result = ""; var index2 = 0; for (var featureIndex in featureList) { if (index2 != 0) { result += ", "; } if (featureList.length > 1 && index2 == (featureList.length - 1)) { result += "and "; } result += featureList[featureIndex]; index2++; } if (!confirm("Some other features require the one you're trying to disable.\n\nSpecifically: " + result + ".\n\nIf you disable this feature without disabling the ones in the list before, *BAD THINGS MIGHT HAPPEN*.\n\n\nAre you sure you want to disable this feature? (***BAD THINGS MIGHT HAPPEN***)")) { $(this).prop("checked", true); return; } } disabledComponentList.push(index); } console.log(disabledComponentList); saveChanges(); }); }); cpal.storage.getKey("backgroundColor", function(result) { if (result === undefined) { return; } $(".background.white").removeClass("selected"); if ($(".background").hasClass(result)) { $(".background." + result).addClass("selected"); } else { $(".background.custom").addClass("selected"); $("#secretColorPicker").val(result); onBgColorPickerChange(); } }); cpal.storage.getKey("backgroundImage", function(result) { if (result === undefined || result === false) { return; } $("#backgroundImagePreview").attr("src", result.url); }); cpal.storage.getKey("textColor", function(result) { if (result === undefined) { return; } $(".textColor.black").removeClass("selected"); if ($(".textColor").hasClass(result)) { $(".textColor." + result).addClass("selected"); } else { $(".textColor.custom").addClass("selected"); $("#secretTextColorPicker").val(result); onTextColorPickerChange(); } }); cpal.storage.getKey("linkTextColor", function(result) { if (result === undefined) { return; } if (result == "#428BCA") { // It's the "bluish" color. return; } $(".linkTextColor.bluish").removeClass("selected"); if ($(".linkTextColor").hasClass(result)) { $(".linkTextColor." + result).addClass("selected"); } else { $(".linkTextColor.custom").addClass("selected"); $("#secretLinkTextColorPicker").val(result); onLinkTextColorPickerChange(); } }); cpal.storage.getKey("navTextColor", function(items) { if (result === undefined) { return; } $(".navTextColor.black").removeClass("selected"); if ($(".navTextColor").hasClass(result)) { $(".navTextColor." + result).addClass("selected"); } else { $(".navTextColor.custom").addClass("selected"); $("#secretNavTextColorPicker").val(result); onNavTextColorPickerChange(); } }); cpal.storage.getKey("logoType", function(logoType) { if (logoType === undefined) { return; } cpal.storage.getKey("logoImage", function(logoImage) { if (logoImage === undefined) { return; } $(".logo.regular").removeClass("selected"); $(".logo." + logoImage).addClass("selected"); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/" + logoImage + ".png")); }); }); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/regular.png")); $.ajax({ url: 'https://coursesplus.tk/usrupl/uplInfo.php', //Server script to process data type: 'POST', dataType: 'json', success: function(res) { $("#bgFileInfo").html(res.typeAndSize); $("#bgPrivacy").html(res.privacy); hideConnecting(); }, error: function(jqXHR, textStatus, errorThrown) { $("#connectingText").text("Unknown error connecting to background image server!"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); } }); $(".selBox").click(function() { if ($(this).hasClass("selected") && !$(this).hasClass("custom")) { // Do nothing return; } console.log($("[data-selBoxGroup=" + $(this).attr("data-selBoxGroup") +"]")); $("[data-selBoxGroup=" + $(this).attr("data-selBoxGroup") +"]").removeClass("selected"); $(this).addClass("selected"); $(this).trigger({ type: "selBoxChanged", to: $(this).attr("data-selBoxVal") }); }); $(".background").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("backgroundColor", e.to); } else { $("#secretColorPicker")[0].click(); } }); $("#secretColorPicker").change(onBgColorPickerChange); $("#secretTextColorPicker").change(onTextColorPickerChange); $("#secretLinkTextColorPicker").change(onLinkTextColorPickerChange); $("#secretNavTextColorPicker").change(onNavTextColorPickerChange); $("#bgImgUplBtn").click(uploadImageAndSetBg); $(".bgSizing").change(function() { saveBgSizing(); }); $("#resetBg").click(function() { cpal.storage.setKey("backgroundImage", false); window.location.reload(); }); $(".textColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("textColor", e.to); } else { $("#secretTextColorPicker")[0].click(); } }); $(".linkTextColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("linkTextColor", e.to); } else { $("#secretLinkTextColorPicker")[0].click(); } }); $(".navTextColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("navTextColor", e.to); } else { $("#secretNavTextColorPicker")[0].click(); } }); $(".logo").on("selBoxChanged" ,function(e) { cpal.storage.setKey("logoType", "preload"); cpal.storage.setKey("logoImage", e.to); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/" + e.to + ".png")); }); $("#selectLogo").click(function() { $("#selLogoModal").modal(); }); var recalcStorage = function() { cpal.storage.quota.getUsedBytes(function(bytes) { $("#storageUsage").text(Math.round((bytes / 1024) * 100) / 100 + " kB out of " + (cpal.storage.quota.getTotalBytes() / 1024) + " kB total used"); }); }; recalcStorage(); $("#clearStorage").click(function() { if (confirm("This will reset Courses+ to its original state, removing all stored information, including completed assignments, course customizations, and more.\n\nAre you SURE you want to clear storage?\nThis action cannot be undone.")) { cpal.storage.clear(function() { recalcStorage(); window.location.reload(); }); } }); cpal.storage.getKey("uniqueId", function(response) { if (response == undefined) { $("#coursesplus-uniqueid").text("not generated yet. Visit a page to have one generated for you."); } else { $("#coursesplus-uniqueid").text(response); } }); $("#importData").click(function() { var response = prompt("THIS WILL REMOVE ALL CURRENTLY STORED DATA.\n\nIf you would like to continue, type in the new data and press OK. Otherwise, press Cancel."); if (response != null) { var responseData = JSON.parse(response); cpal.storage.clear(function() { for (var key in responseData) { cpal.storage.setKey(key, responseData[key], function() {}); } }); } }); $("#exportData").click(function() { cpal.storage.getAll(function(items) { prompt("Here is all the information Courses+ has stored in JSON format.", JSON.stringify(items)); }); }); });
js/options.js
var disabledComponentList = []; function saveChanges() { cpal.storage.setKey("disabledComponents", disabledComponentList, function() { console.log("Saved changes!"); }); } function createList(sortedComponents, $ulToAppendTo, checkList, checkPresence, clickEvent) { //var sortedComponents = window.components; for (var componentIndex in sortedComponents) { if (componentIndex == "runAll") { continue; } var component = sortedComponents[componentIndex]; var $appendMeReally = $('<li class="col-1-4 feature"></li>'); $appendMeReally.attr("data-componentIndex", componentIndex); var $appendMe = $('<div class="content"></div>'); $appendMe.addClass("feature"); var $check = $("<input type=\"checkbox\" />"); $check.addClass("featureCheck"); $check.prop("checked", (checkPresence ? checkList.indexOf(componentIndex) != -1 : checkList.indexOf(componentIndex) == -1)); $check.attr("data-index", componentIndex); $check.click(clickEvent); $appendMe.append($check); var $label = $("<strong></strong>"); $label.addClass("featureLabel"); $label.html(/*"&nbsp;" + */component.displayName); $appendMe.append($label); var $desc = $("<p></p>"); $desc.addClass("featureDesc"); $desc.html(component.description); $appendMe.append($("<br />")); $appendMe.append($desc); var $req = $("<p></p>"); $req.addClass("featureReq"); if (component.requires.length > 0) { var result = "This feature requires "; $.each(component.requires, function(index) { if (index != 0) { result += ","; } if (component.requires.length > 1 && index == (component.requires.length - 1)) { result += " and "; } firstOne = false; result += components[this].displayName; }); result += " to be enabled."; $req.html(result); $appendMe.append($req); } $appendMeReally.append($appendMe) $ulToAppendTo.append($appendMeReally); } } function progressHandlingFunction(e) { console.log(e); if(e.lengthComputable){ //$('progress').attr({value:e.loaded,max:e.total}); } } function saveBgUrlSizing(url) { cpal.storage.setKey("backgroundImage", { url: url, sizing: $(".bgSizing:checked").val() }); } function saveBgSizing() { if ($("#backgroundImagePreview").attr("src") != "images/nobg.png") { saveBgUrlSizing($("#backgroundImagePreview").attr("src")); } } function showLoading() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").hide(); $("#uploadingText").show(); } function hideLoading() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").show(); $("#uploadingText").hide(); } function hideConnecting() { $("#bgImgUpl > *").not("#uploadingText").not("#connectingText").show(); $("#connectingText").hide(); } function uploadImageAndSetBg() { if ($("#fileToUpload").val() == "") { alert("Please select an image with the Choose File button! (above the green Upload Image button)"); return false; } showLoading(); var formData = new FormData($('form')[0]); $.ajax({ url: 'https://coursesplus.tk/usrupl/uploadFilePost.php', //Server script to process data type: 'POST', data: formData, cache: false, dataType: 'json', xhr: function() { // Custom XMLHttpRequest var myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { // Check if upload property exists myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload } return myXhr; }, //Ajax events //beforeSend: beforeSendHandler, success: function(res) { if (res.error) { alert("Error uploading image - " + res.errorMsg); hideLoading(); window.location.reload(); return; } $("#backgroundImagePreview").attr("src", res.url); hideLoading(); saveBgSizing(); console.log("Image uploaded to " + res.url + "!"); }, error: function(jqXHR, textStatus, errorThrown) { hideLoading(); alert("Unknown error uploading image!"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); window.location.reload(); }, // Options to tell jQuery not to process data or worry about content-type. contentType: false, processData: false }); return false; } var onBgColorPickerChange = function() { var newColor = $("#secretColorPicker").val(); $(".background.custom").css("background-color", newColor); $(".background.custom").css("color", newColor); cpal.storage.setKey("backgroundColor", newColor); }; var onTextColorPickerChange = function() { var newColor = $("#secretTextColorPicker").val(); $(".textColor.custom").css("background-color", newColor); $(".textColor.custom").css("color", newColor); cpal.storage.setKey("textColor", newColor); }; var onLinkTextColorPickerChange = function() { var newColor = $("#secretLinkTextColorPicker").val(); $(".linkTextColor.custom").css("background-color", newColor); $(".linkTextColor.custom").css("color", newColor); cpal.storage.setKey("linkTextColor", newColor); }; var onNavTextColorPickerChange = function() { var newColor = $("#secretNavTextColorPicker").val(); $(".navTextColor.custom").css("background-color", newColor); $(".navTextColor.custom").css("color", newColor); cpal.storage.setKey("navTextColor", newColor); }; function handleServicePart2(index, thisService) { console.log("All permissions done!"); cpal.storage.getKey("services", function(result) { serviceList = ($.isArray(result) ? result : []); console.log(serviceList); serviceList.push(index); cpal.storage.setKey("services", serviceList, function() { thisService.onEnable(); }); }); } $(document).ready(function() { cpal.storage.getKey("services", function(result) { var serviceList = ($.isArray(result) ? result : []); createList(window.services, $("#services > ul"), serviceList, true, function() { var index = $(this).attr("data-index"); var $this = $(this); var thisService = window.services[index]; if ($(this).prop("checked")) { if (thisService.origins != []) { // TODO: cpal // Do we have them? console.log("Asking for permissions..."); chrome.permissions.contains({ permissions: [], origins: thisService.origins }, function(result) { if (result) { // Done with permission stuff! handleServicePart2(index, thisService); } else { // OK, let's ask. chrome.permissions.request({ permissions: [], origins: thisService.origins }, function(granted) { if (granted) { // YAAAY handleServicePart2(index, thisService); } else { $this.prop("checked", false); alert(thisService.displayName + " requires those permissions."); } }); } }); } else { handleServicePart2(index, thisService); } } else { cpal.storage.getKey("services", function(result) { serviceList = ($.isArray(result) ? result : []); serviceList.splice(serviceList.indexOf($(this).attr("data-index")), 1); cpal.storage.setKey("services", serviceList, function() { }); }); thisService.onDisable(); } }); }); cpal.storage.getKey("disabledComponents", function(result) { disabledComponentList = ($.isArray(result) ? result : []); console.log(disabledComponentList); createList(window.components, $("#features > ul"), disabledComponentList, false, function() { var sortedComponents = window.components; var index = $(this).attr("data-index"); var featureList = []; for (var checkInd in sortedComponents) { if (checkInd == "createErrorModal" || checkInd == "runAll") { continue; } if (sortedComponents[checkInd].requires.indexOf(index) != -1) { featureList.push(sortedComponents[checkInd].displayName); } } if ($(this).prop("checked")) { disabledComponentList.splice(disabledComponentList.indexOf(index), 1); } else { if (featureList.length > 0) { var result = ""; var index2 = 0; for (var featureIndex in featureList) { if (index2 != 0) { result += ", "; } if (featureList.length > 1 && index2 == (featureList.length - 1)) { result += "and "; } result += featureList[featureIndex]; index2++; } if (!confirm("Some other features require the one you're trying to disable.\n\nSpecifically: " + result + ".\n\nIf you disable this feature without disabling the ones in the list before, *BAD THINGS MIGHT HAPPEN*.\n\n\nAre you sure you want to disable this feature? (***BAD THINGS MIGHT HAPPEN***)")) { $(this).prop("checked", true); return; } } disabledComponentList.push(index); } console.log(disabledComponentList); saveChanges(); }); }); cpal.storage.getKey("backgroundColor", function(result) { if (result === undefined) { return; } $(".background.white").removeClass("selected"); if ($(".background").hasClass(result)) { $(".background." + result).addClass("selected"); } else { $(".background.custom").addClass("selected"); $("#secretColorPicker").val(result); onBgColorPickerChange(); } }); cpal.storage.getKey("backgroundImage", function(result) { if (result === undefined || result === false) { return; } $("#backgroundImagePreview").attr("src", result.url); }); cpal.storage.getKey("textColor", function(result) { if (result === undefined) { return; } $(".textColor.black").removeClass("selected"); if ($(".textColor").hasClass(result)) { $(".textColor." + result).addClass("selected"); } else { $(".textColor.custom").addClass("selected"); $("#secretTextColorPicker").val(result); onTextColorPickerChange(); } }); cpal.storage.getKey("linkTextColor", function(result) { if (result === undefined) { return; } if (result == "#428BCA") { // It's the "bluish" color. return; } $(".linkTextColor.bluish").removeClass("selected"); if ($(".linkTextColor").hasClass(result)) { $(".linkTextColor." + result).addClass("selected"); } else { $(".linkTextColor.custom").addClass("selected"); $("#secretLinkTextColorPicker").val(result); onLinkTextColorPickerChange(); } }); cpal.storage.getKey("navTextColor", function(items) { if (result === undefined) { return; } $(".navTextColor.black").removeClass("selected"); if ($(".navTextColor").hasClass(result)) { $(".navTextColor." + result).addClass("selected"); } else { $(".navTextColor.custom").addClass("selected"); $("#secretNavTextColorPicker").val(result); onNavTextColorPickerChange(); } }); cpal.storage.getKey("logoType", function(logoType) { if (logoType === undefined) { return; } cpal.storage.getKey("logoImage", function(logoImage) { if (logoImage === undefined) { return; } $(".logo.regular").removeClass("selected"); $(".logo." + logoImage).addClass("selected"); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/" + logoImage + ".png")); }); }); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/regular.png")); $.ajax({ url: 'https://coursesplus.tk/usrupl/uplInfo.php', //Server script to process data type: 'POST', dataType: 'json', success: function(res) { $("#bgFileInfo").html(res.typeAndSize); $("#bgPrivacy").html(res.privacy); hideConnecting(); }, error: function(jqXHR, textStatus, errorThrown) { $("#connectingText").text("Unknown error connecting to background image server!"); console.log(jqXHR); console.log(textStatus); console.log(errorThrown); } }); $(".selBox").click(function() { if ($(this).hasClass("selected") && !$(this).hasClass("custom")) { // Do nothing return; } console.log($("[data-selBoxGroup=" + $(this).attr("data-selBoxGroup") +"]")); $("[data-selBoxGroup=" + $(this).attr("data-selBoxGroup") +"]").removeClass("selected"); $(this).addClass("selected"); $(this).trigger({ type: "selBoxChanged", to: $(this).attr("data-selBoxVal") }); }); $(".background").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("backgroundColor", e.to); } else { $("#secretColorPicker")[0].click(); } }); $("#secretColorPicker").change(onBgColorPickerChange); $("#secretTextColorPicker").change(onTextColorPickerChange); $("#secretLinkTextColorPicker").change(onLinkTextColorPickerChange); $("#secretNavTextColorPicker").change(onNavTextColorPickerChange); $("#bgImgUplBtn").click(uploadImageAndSetBg); $(".bgSizing").change(function() { saveBgSizing(); }); $("#resetBg").click(function() { cpal.storage.setKey("backgroundImage", false); window.location.reload(); }); $(".textColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("textColor", e.to); } else { $("#secretTextColorPicker")[0].click(); } }); $(".linkTextColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("linkTextColor", e.to); } else { $("#secretLinkTextColorPicker")[0].click(); } }); $(".navTextColor").on("selBoxChanged", function(e) { if (e.to != "custom") { cpal.storage.setKey("navTextColor", e.to); } else { $("#secretNavTextColorPicker")[0].click(); } }); $(".logo").on("selBoxChanged" ,function(e) { cpal.storage.setKey("logoType", "preload"); cpal.storage.setKey("logoImage", e.to); $(".selectedLogo").attr("src", cpal.resources.getURL("images/logos/" + e.to + ".png")); }); $("#selectLogo").click(function() { $("#selLogoModal").modal(); }); var recalcStorage = function() { cpal.storage.quota.getUsedBytes(function(bytes) { $("#storageUsage").text(Math.round((bytes / 1024) * 100) / 100 + " kB out of " + (cpal.storage.quota.getTotalBytes() / 1024) + " kB total used"); }); }; recalcStorage(); $("#clearStorage").click(function() { if (confirm("This will reset Courses+ to its original state, removing all stored information, including completed assignments, course customizations, and more.\n\nAre you SURE you want to clear storage?\nThis action cannot be undone.")) { cpal.storage.clear(function() { recalcStorage(); window.location.reload(); }); } }); cpal.storage.getKey("uniqueId", function(response) { if (response == undefined) { $("#coursesplus-uniqueid").text("not generated yet. Visit a page to have one generated for you."); } else { $("#coursesplus-uniqueid").text(response); } }); $("#importData").click(function() { var response = prompt("THIS WILL REMOVE ALL CURRENTLY STORED DATA.\n\nIf you would like to continue, type in the new data and press OK. Otherwise, press Cancel."); if (response != null) { var responseData = JSON.parse(response); cpal.storage.clear(function() { for (var key in responseData) { cpal.storage.setKey(key, responseData[key], function() {}); } }); } }); $("#exportData").click(function() { cpal.storage.getAll(function(items) { prompt("Here is all the information Courses+ has stored in JSON format.", JSON.stringify(items)); }); }); });
Fix removing services not working right
js/options.js
Fix removing services not working right
<ide><path>s/options.js <ide> handleServicePart2(index, thisService); <ide> } <ide> } else { <add> var componentIndex = $(this).attr("data-index"); <ide> cpal.storage.getKey("services", function(result) { <ide> serviceList = ($.isArray(result) ? result : []); <del> serviceList.splice(serviceList.indexOf($(this).attr("data-index")), 1); <add> console.log(componentIndex); <add> serviceList.splice(serviceList.indexOf(componentIndex), 1); <ide> cpal.storage.setKey("services", serviceList, function() { <ide> <ide> });
Java
apache-2.0
59280f1df6caa4e302ed11926fd253d2c5544efb
0
marcust/stagemonitor,sdgdsffdsfff/stagemonitor,glamarre360/stagemonitor,elevennl/stagemonitor,marcust/stagemonitor,trampi/stagemonitor,stagemonitor/stagemonitor,sdgdsffdsfff/stagemonitor,glamarre360/stagemonitor,hexdecteam/stagemonitor,glamarre360/stagemonitor,stagemonitor/stagemonitor,marcust/stagemonitor,elevennl/stagemonitor,sdgdsffdsfff/stagemonitor,stagemonitor/stagemonitor,elevennl/stagemonitor,trampi/stagemonitor,stagemonitor/stagemonitor,marcust/stagemonitor,trampi/stagemonitor,glamarre360/stagemonitor,hexdecteam/stagemonitor,trampi/stagemonitor,hexdecteam/stagemonitor,hexdecteam/stagemonitor,elevennl/stagemonitor,sdgdsffdsfff/stagemonitor
package org.stagemonitor.collector.core; import com.codahale.metrics.*; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.stagemonitor.collector.core.metrics.SortedTableLogReporter; import org.stagemonitor.entities.MeasurementSession; import java.net.InetSocketAddress; import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.codahale.metrics.MetricRegistry.name; import static org.stagemonitor.util.GraphiteEncoder.encodeForGraphite; public class StageMonitorApplicationContext { private final static Log logger = LogFactory.getLog(StageMonitorApplicationContext.class); private static Configuration configuration = new Configuration(); private static AtomicBoolean started = new AtomicBoolean(false); public synchronized static boolean startMonitoring(MeasurementSession measurementSession) { if (started.get()) { return true; } if (measurementSession.isInitialized() && !started.get()) { initializePlugins(); applyExcludePatterns(); reportToGraphite(configuration.getGraphiteReportingInterval(), measurementSession); reportToConsole(configuration.getConsoleReportingInterval()); if (configuration.reportToJMX()) { reportToJMX(); } logger.info("Measurement Session is initialized: " + measurementSession); started.set(true); return true; } else { logger.warn("Measurement Session is not initialized: " + measurementSession); logger.warn("make sure the properties 'stagemonitor.instanceName' and 'stagemonitor.applicationName' are set and stagemonitor.properties is available in the classpath"); return false; } } private static void applyExcludePatterns() { for (final String excludePattern : configuration.getExcludedMetricsPatterns()) { getMetricRegistry().removeMatching(new MetricFilter() { @Override public boolean matches(String name, Metric metric) { return name.matches(excludePattern); } }); } } private static void initializePlugins() { for (StageMonitorPlugin stagemonitorPlugin : ServiceLoader.load(StageMonitorPlugin.class)) { stagemonitorPlugin.initializePlugin(getMetricRegistry(), getConfiguration()); } } public static MetricRegistry getMetricRegistry() { return SharedMetricRegistries.getOrCreate("stagemonitor"); } private static void reportToGraphite(long reportingInterval, MeasurementSession measurementSession) { String graphiteHostName = configuration.getGraphiteHostName(); if (graphiteHostName != null && !graphiteHostName.isEmpty()) { final Graphite graphite = new Graphite(new InetSocketAddress(graphiteHostName, configuration.getGraphitePort())); GraphiteReporter.forRegistry(getMetricRegistry()) .prefixedWith(getGraphitePrefix(measurementSession)) .convertRatesTo(TimeUnit.MINUTES) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(new MetricsWithCountFilter()) .build(graphite) .start(reportingInterval, TimeUnit.SECONDS); } } private static String getGraphitePrefix(MeasurementSession measurementSession) { return name("stagemonitor", encodeForGraphite(measurementSession.getApplicationName()), encodeForGraphite(measurementSession.getInstanceName()), encodeForGraphite(measurementSession.getHostName())); } private static void reportToConsole(long reportingInterval) { if (reportingInterval > 0) { SortedTableLogReporter.forRegistry(getMetricRegistry()) .convertRatesTo(TimeUnit.MINUTES) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(new MetricsWithCountFilter()) .build() .start(reportingInterval, TimeUnit.SECONDS); } } private static void reportToJMX() { JmxReporter.forRegistry(getMetricRegistry()) .filter(new MetricsWithCountFilter()) .build().start(); } public static Configuration getConfiguration() { return configuration; } private static class MetricsWithCountFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (metric instanceof Metered) { return ((Metered) metric).getCount() > 0; } return true; } } }
stagemonitor-collector/stagemonitor-collector-core/src/main/java/org/stagemonitor/collector/core/StageMonitorApplicationContext.java
package org.stagemonitor.collector.core; import com.codahale.metrics.JmxReporter; import com.codahale.metrics.Metered; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.SharedMetricRegistries; import com.codahale.metrics.graphite.Graphite; import com.codahale.metrics.graphite.GraphiteReporter; import org.stagemonitor.collector.core.metrics.SortedTableLogReporter; import org.stagemonitor.entities.MeasurementSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.net.InetSocketAddress; import java.util.ServiceLoader; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.codahale.metrics.MetricRegistry.name; import static org.stagemonitor.util.GraphiteEncoder.encodeForGraphite; public class StageMonitorApplicationContext { private final static Log logger = LogFactory.getLog(StageMonitorApplicationContext.class); private static Configuration configuration = new Configuration(); private static AtomicBoolean started = new AtomicBoolean(false); public synchronized static boolean startMonitoring(MeasurementSession measurementSession) { if (started.get()) { return true; } if (measurementSession.isInitialized() && !started.get()) { initializePlugins(); applyExcludePatterns(); reportToGraphite(configuration.getGraphiteReportingInterval(), measurementSession); reportToConsole(configuration.getConsoleReportingInterval()); if (configuration.reportToJMX()) { reportToJMX(); } logger.info("Measurement Session is initialized: " + measurementSession); started.set(true); return true; } else { logger.warn("Measurement Session is not initialized: " + measurementSession); logger.warn("make sure the properties 'stagemonitor.instanceName' and 'stagemonitor.applicationName' are set and stagemonitor.properties is available in the classpath"); return false; } } private static void applyExcludePatterns() { for (final String excludePattern : configuration.getExcludedMetricsPatterns()) { getMetricRegistry().removeMatching(new MetricFilter() { @Override public boolean matches(String name, Metric metric) { return name.matches(excludePattern); } }); } } private static void initializePlugins() { for (StageMonitorPlugin stagemonitorPlugin : ServiceLoader.load(StageMonitorPlugin.class)) { stagemonitorPlugin.initializePlugin(getMetricRegistry(), getConfiguration()); } } public static MetricRegistry getMetricRegistry() { return SharedMetricRegistries.getOrCreate("stagemonitor"); } private static void reportToGraphite(long reportingInterval, MeasurementSession measurementSession) { String graphiteHostName = configuration.getGraphiteHostName(); if (graphiteHostName != null && !graphiteHostName.isEmpty()) { final Graphite graphite = new Graphite(new InetSocketAddress(graphiteHostName, configuration.getGraphitePort())); GraphiteReporter.forRegistry(getMetricRegistry()) .prefixedWith(getGraphitePrefix(measurementSession)) .convertRatesTo(TimeUnit.MINUTES) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(new MetricsWithCountFilter()) .build(graphite) .start(reportingInterval, TimeUnit.SECONDS); } } private static String getGraphitePrefix(MeasurementSession measurementSession) { return name("stagemonitor", encodeForGraphite(measurementSession.getApplicationName()), encodeForGraphite(measurementSession.getInstanceName()), encodeForGraphite(measurementSession.getHostName())); } private static void reportToConsole(long reportingInterval) { if (reportingInterval > 0) { SortedTableLogReporter.forRegistry(getMetricRegistry()) .convertRatesTo(TimeUnit.MINUTES) .convertDurationsTo(TimeUnit.MILLISECONDS) .filter(new MetricsWithCountFilter()) .build() .start(reportingInterval, TimeUnit.SECONDS); } } private static void reportToJMX() { JmxReporter.forRegistry(getMetricRegistry()).build().start(); } public static Configuration getConfiguration() { return configuration; } private static class MetricsWithCountFilter implements MetricFilter { @Override public boolean matches(String name, Metric metric) { if (metric instanceof Metered) { return ((Metered) metric).getCount() > 0; } return true; } } }
added MetricsWithCountFilter to JMX reporter
stagemonitor-collector/stagemonitor-collector-core/src/main/java/org/stagemonitor/collector/core/StageMonitorApplicationContext.java
added MetricsWithCountFilter to JMX reporter
<ide><path>tagemonitor-collector/stagemonitor-collector-core/src/main/java/org/stagemonitor/collector/core/StageMonitorApplicationContext.java <ide> package org.stagemonitor.collector.core; <ide> <del>import com.codahale.metrics.JmxReporter; <del>import com.codahale.metrics.Metered; <del>import com.codahale.metrics.Metric; <del>import com.codahale.metrics.MetricFilter; <del>import com.codahale.metrics.MetricRegistry; <del>import com.codahale.metrics.SharedMetricRegistries; <add>import com.codahale.metrics.*; <ide> import com.codahale.metrics.graphite.Graphite; <ide> import com.codahale.metrics.graphite.GraphiteReporter; <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <ide> import org.stagemonitor.collector.core.metrics.SortedTableLogReporter; <ide> import org.stagemonitor.entities.MeasurementSession; <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <ide> <ide> import java.net.InetSocketAddress; <ide> import java.util.ServiceLoader; <ide> } <ide> <ide> private static void reportToJMX() { <del> JmxReporter.forRegistry(getMetricRegistry()).build().start(); <add> JmxReporter.forRegistry(getMetricRegistry()) <add> .filter(new MetricsWithCountFilter()) <add> .build().start(); <ide> } <ide> <ide> public static Configuration getConfiguration() {
Java
apache-2.0
4b533d34d94973060889daf2181d51eee86fadef
0
sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl,sarl/sarl
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2020 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.m2e.config; import java.io.File; import java.text.MessageFormat; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import com.google.common.base.Strings; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.internal.M2EUtils; import org.eclipse.m2e.core.lifecyclemapping.model.IPluginExecutionMetadata; import org.eclipse.m2e.core.project.IMavenProjectFacade; import org.eclipse.m2e.core.project.MavenProjectUtils; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant2; import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator; import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest; import org.eclipse.m2e.jdt.IClasspathDescriptor; import org.eclipse.m2e.jdt.IClasspathEntryDescriptor; import org.eclipse.m2e.jdt.IJavaProjectConfigurator; import org.eclipse.m2e.jdt.internal.ClasspathDescriptor; import org.osgi.framework.Bundle; import org.osgi.framework.Version; import org.sonatype.plexus.build.incremental.BuildContext; import io.sarl.eclipse.SARLEclipseConfig; import io.sarl.eclipse.buildpath.SARLClasspathContainerInitializer; import io.sarl.eclipse.util.Utilities; import io.sarl.lang.SARLConfig; import io.sarl.lang.SARLVersion; import io.sarl.lang.ui.preferences.SARLPreferences; import io.sarl.m2e.utils.M2EUtilities; /** Project configuration for the M2E. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public class SARLProjectConfigurator extends AbstractProjectConfigurator implements IJavaProjectConfigurator { private static final String SARL_LANG_BUNDLE_NAME = "io.sarl.lang.core"; //$NON-NLS-1$ private static final String SARL_GROUP_ID = "io.sarl.lang"; //$NON-NLS-1$ private static final String SARL_ARTIFACT_ID = "io.sarl.lang.core"; //$NON-NLS-1$ private static final String SARL_MAVENLIB_GROUP_ID = "io.sarl.maven"; //$NON-NLS-1$ private static final String SARL_MAVENLIB_ARTIFACT_ID = "io.sarl.maven.sdk"; //$NON-NLS-1$ private static final String SARL_PLUGIN_GROUP_ID = "io.sarl.maven"; //$NON-NLS-1$ private static final String SARL_PLUGIN_ARTIFACT_ID = "sarl-maven-plugin"; //$NON-NLS-1$ private static final String ECLIPSE_PLUGIN_PACKAGING = "eclipse-plugin"; //$NON-NLS-1$ /** Invoked to add the preferences dedicated to SARL, JRE, etc. * * @param facade the Maven face. * @param config the configuration. * @param addTestFolders indicates if the test folders should be considered. * @param monitor the monitor. * @throws CoreException if cannot add the source folders. */ @SuppressWarnings("static-method") protected void addPreferences( IMavenProjectFacade facade, SARLConfiguration config, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { final IPath outputPath = makeProjectRelativePath(facade, config.getOutput()); final IPath testOutputPath = addTestFolders ? makeProjectRelativePath(facade, config.getTestOutput()) : null; // Set the SARL preferences SARLPreferences.setSpecificSARLConfigurationFor( facade.getProject(), outputPath, testOutputPath); } private static IPath makeFullPath(IMavenProjectFacade facade, File file) { assert file != null; final IProject project = facade.getProject(); final IPath path; if (!file.isAbsolute()) { path = Path.fromOSString(file.getPath()); } else { path = MavenProjectUtils.getProjectRelativePath(project, file.getAbsolutePath()); } return project.getFullPath().append(path); } private static IPath makeProjectRelativePath(IMavenProjectFacade facade, File file) { assert file != null; final IProject project = facade.getProject(); if (!file.isAbsolute()) { return Path.fromOSString(file.getPath()); } return MavenProjectUtils.getProjectRelativePath(project, file.getAbsolutePath()); } private static IFolder ensureFolderExists(IMavenProjectFacade facade, IPath path, boolean derived, IProgressMonitor monitor) throws CoreException { final IFolder folder = facade.getProject().getFolder(path.makeRelativeTo(facade.getProject().getFullPath())); assert folder != null; if (!folder.exists()) { M2EUtils.createFolder(folder, derived || folder.isDerived(), monitor); } return folder; } /** Invoked to add the source folders. * * @param facade the facade of the Maven project. * @param config the configuration. * @param classpath the project classpath. * @param addTestFolders indicate if the test folders must be added into the classpath. * @param monitor the monitor. * @throws CoreException if cannot add the source folders. */ @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:npathcomplexity"}) protected void addSourceFolders( IMavenProjectFacade facade, SARLConfiguration config, IClasspathDescriptor classpath, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { assertHasNature(facade.getProject(), SARLEclipseConfig.NATURE_ID); assertHasNature(facade.getProject(), SARLEclipseConfig.XTEXT_NATURE_ID); assertHasNature(facade.getProject(), JavaCore.NATURE_ID); final String encoding = config.getEncoding(); final SubMonitor subMonitor = SubMonitor.convert(monitor, 4); // // Add the source folders // // Input folder, e.g. "src/main/sarl" final IPath inputPath = makeFullPath(facade, config.getInput()); final IFolder inputFolder = ensureFolderExists(facade, inputPath, false, subMonitor); if (encoding != null && inputFolder != null && inputFolder.exists()) { inputFolder.setDefaultCharset(encoding, monitor); } IClasspathEntryDescriptor descriptor = classpath.addSourceEntry( inputPath, facade.getOutputLocation(), false); descriptor.setPomDerived(true); subMonitor.worked(1); // Input folder, e.g. "src/main/generated-sources/sarl" final IPath outputPath = makeFullPath(facade, config.getOutput()); final IFolder outputFolder = ensureFolderExists(facade, outputPath, true, subMonitor); if (encoding != null && outputFolder != null && outputFolder.exists()) { outputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( outputPath, facade.getOutputLocation(), false); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, Boolean.TRUE.toString()); subMonitor.worked(1); if (addTestFolders) { // Test input folder, e.g. "src/test/sarl" final IPath testInputPath = makeFullPath(facade, config.getTestInput()); final IFolder testInputFolder = ensureFolderExists(facade, testInputPath, false, subMonitor); if (encoding != null && testInputFolder != null && testInputFolder.exists()) { testInputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( testInputPath, facade.getTestOutputLocation(), true); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.TEST, Boolean.TRUE.toString()); } subMonitor.worked(1); if (addTestFolders) { // Test input folder, e.g. "src/test/generated-sources/sarl" final IPath testOutputPath = makeFullPath(facade, config.getTestOutput()); final IFolder testOutputFolder = ensureFolderExists(facade, testOutputPath, true, subMonitor); if (encoding != null && testOutputFolder != null && testOutputFolder.exists()) { testOutputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( testOutputPath, facade.getTestOutputLocation(), true); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, Boolean.TRUE.toString()); descriptor.setClasspathAttribute(IClasspathAttribute.TEST, Boolean.TRUE.toString()); } subMonitor.done(); } /** Replies the configuration value. * * @param <T> - the expected type. * @param project the project. * @param parameter the parameter name. * @param asType the expected type. * @param mojoExecution the mojo execution. * @param monitor the monitor. * @param defaultValue the default value. * @return the value of the parameter. * @throws CoreException if cannot read the value. */ protected <T> T getParameterValue(MavenProject project, String parameter, Class<T> asType, MojoExecution mojoExecution, IProgressMonitor monitor, T defaultValue) throws CoreException { T value = getParameterValue(project, parameter, asType, mojoExecution, monitor); if (value == null) { value = defaultValue; } return value; } /** Read the SARL configuration. * * @param request the configuration request. * @param monitor the monitor. * @return the SARL configuration. * @throws CoreException if something wrong appends. */ protected SARLConfiguration readConfiguration(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { SARLConfiguration initConfig = null; SARLConfiguration compileConfig = null; final List<MojoExecution> mojos = getMojoExecutions(request, monitor); for (final MojoExecution mojo : mojos) { final String goal = mojo.getGoal(); switch (goal) { case "initialize": //$NON-NLS-1$ initConfig = readInitializeConfiguration(request, mojo, monitor); break; case "compile": //$NON-NLS-1$ case "testCompile": //$NON-NLS-1$ compileConfig = readCompileConfiguration(request, mojo, monitor); break; default: } } if (compileConfig != null && initConfig != null) { compileConfig.setFrom(initConfig); } return compileConfig; } /** Read the configuration for the Initialize mojo. * * @param request the request. * @param mojo the mojo execution. * @param monitor the monitor. * @return the configuration. * @throws CoreException error in the eCore configuration. */ private SARLConfiguration readInitializeConfiguration( ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor) throws CoreException { final SARLConfiguration config = new SARLConfiguration(); final MavenProject project = request.getMavenProject(); final File input = getParameterValue(project, "input", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_SOURCE_SARL)); final File output = getParameterValue(project, "output", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_SOURCE_GENERATED)); final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_BIN)); final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_SOURCE_SARL)); final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_SOURCE_GENERATED)); final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_BIN)); config.setInput(input); config.setOutput(output); config.setBinOutput(binOutput); config.setTestInput(testInput); config.setTestOutput(testOutput); config.setTestBinOutput(testBinOutput); return config; } /** Read the configuration for the Compilation mojo. * * @param request the request. * @param mojo the mojo execution. * @param monitor the monitor. * @return the configuration. * @throws CoreException error in the eCore configuration. */ private SARLConfiguration readCompileConfiguration( ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor) throws CoreException { final SARLConfiguration config = new SARLConfiguration(); final MavenProject project = request.getMavenProject(); final File input = getParameterValue(project, "input", File.class, mojo, monitor); //$NON-NLS-1$ final File output = getParameterValue(project, "output", File.class, mojo, monitor); //$NON-NLS-1$ final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor); //$NON-NLS-1$ final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor); //$NON-NLS-1$ final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor); //$NON-NLS-1$ final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor); //$NON-NLS-1$ config.setInput(input); config.setOutput(output); config.setBinOutput(binOutput); config.setTestInput(testInput); config.setTestOutput(testOutput); config.setTestBinOutput(testBinOutput); final String inputCompliance = getParameterValue(project, "source", String.class, mojo, monitor); //$NON-NLS-1$ final String outputCompliance = getParameterValue(project, "target", String.class, mojo, monitor); //$NON-NLS-1$ config.setInputCompliance(inputCompliance); config.setOutputCompliance(outputCompliance); final String encoding = getParameterValue(project, "encoding", String.class, mojo, monitor); //$NON-NLS-1$ config.setEncoding(encoding); return config; } /** Remove any reference to the SARL libraries from the given classpath. * * @param classpath the classpath to update. */ @SuppressWarnings("static-method") protected void removeSarlLibraries(IClasspathDescriptor classpath) { classpath.removeEntry(SARLClasspathContainerInitializer.CONTAINER_ID); } /** Add the SARL libraries into the given classpath. * * @param classpath the classpath to update. */ @SuppressWarnings("static-method") protected void addSarlLibraries(IClasspathDescriptor classpath) { final IClasspathEntry entry = JavaCore.newContainerEntry(SARLClasspathContainerInitializer.CONTAINER_ID); classpath.addEntry(entry); } private static void setVersion(Properties props, String propName, String value, String minValue, String incompatibleValue) { final String currentVersion = props.getProperty(propName); String newVersion = value; if (M2EUtilities.compareOsgiVersions(currentVersion, newVersion) > 0) { newVersion = currentVersion; } if (M2EUtilities.compareOsgiVersions(newVersion, minValue) < 0) { props.setProperty(propName, minValue); } else if (M2EUtilities.compareOsgiVersions(newVersion, incompatibleValue) >= 0) { props.setProperty(propName, M2EUtilities.getPreviousOsgiVersion(incompatibleValue)); } else { props.setProperty(propName, newVersion); } } private static void forceMavenCompilerConfiguration(IMavenProjectFacade facade, SARLConfiguration config) { final Properties props = facade.getMavenProject().getProperties(); setVersion(props, "maven.compiler.source", config.getInputCompliance(), //$NON-NLS-1$ SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT, SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT); setVersion(props, "maven.compiler.target", config.getOutputCompliance(), //$NON-NLS-1$ SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT, SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT); final String encoding = config.getEncoding(); if (encoding != null && !encoding.isEmpty()) { props.setProperty("maven.compiler.encoding", encoding); //$NON-NLS-1$ } } /** Replies if the given project facade is pointing an Eclipe plugin. * * @param facade the maven project facade. * @return {@code true} if the facade is for an Eclipse plugin. * @since 0.11 */ public boolean isEclipsePluginPackaging(IMavenProjectFacade facade) { return ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(facade.getPackaging()); } @Override @SuppressWarnings("checkstyle:magicnumber") public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { final IMavenProjectFacade facade = request.getMavenProjectFacade(); // --- ECLIPSE PLUGIN --------------------------------------------------------------- // Special case of tycho plugins, for which the {@link #configureRawClasspath} // and {@link #configureClasspath} were not invoked. // ---------------------------------------------------------------------------------- final boolean isEclipsePlugin = isEclipsePluginPackaging(facade); final SubMonitor subMonitor; if (isEclipsePlugin) { subMonitor = SubMonitor.convert(monitor, 4); } else { subMonitor = SubMonitor.convert(monitor, 3); } final IProject project = request.getProject(); final SARLConfiguration config = readConfiguration(request, subMonitor.newChild(1)); subMonitor.worked(1); forceMavenCompilerConfiguration(facade, config); subMonitor.worked(1); // --- ECLIPSE PLUGIN --------------------------------------------------------------- if (isEclipsePlugin) { // In the case of Eclipse bundle, the face to the Java project must be created by hand. final IJavaProject javaProject = JavaCore.create(project); final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject); configureSarlProject(facade, config, classpath, false, subMonitor.newChild(1)); subMonitor.worked(1); } // ---------------------------------------------------------------------------------- io.sarl.eclipse.natures.SARLProjectConfigurator.addSarlNatures( project, subMonitor.newChild(1)); subMonitor.worked(1); } private void configureSarlProject(IMavenProjectFacade facade, SARLConfiguration config, IClasspathDescriptor classpath, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 2); addSourceFolders(facade, config, classpath, addTestFolders, subm.newChild(1)); subm.worked(1); addPreferences(facade, config, addTestFolders, subm.newChild(1)); subm.worked(1); } @Override public void unconfigure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { final IJavaProject javaProject = JavaCore.create(request.getProject()); final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject); addSarlLibraries(classpath); } @Override public void configureClasspath(IMavenProjectFacade facade, IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException { // } @Override public void configureRawClasspath(ProjectConfigurationRequest request, IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 4); final IMavenProjectFacade facade = request.getMavenProjectFacade(); final SARLConfiguration config = readConfiguration(request, subm.newChild(1)); subm.worked(1); removeSarlLibraries(classpath); subm.worked(2); configureSarlProject(facade, config, classpath, true, subm); } @Override public AbstractBuildParticipant getBuildParticipant( IMavenProjectFacade projectFacade, MojoExecution execution, IPluginExecutionMetadata executionMetadata) { return new BuildParticipant(isEclipsePluginPackaging(projectFacade)); } /** Build participant for detecting invalid versions of SARL components. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ protected static class BuildParticipant extends AbstractBuildParticipant2 { private static final int NSTEPS = 4; private final boolean isEclipsePlugin; /** Construct a build participant. * * @param isEclipsePlugin indicates if the build participant is created for an Eclipse plugin project. */ public BuildParticipant(boolean isEclipsePlugin) { this.isEclipsePlugin = isEclipsePlugin; } @Override public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception { if (kind == AbstractBuildParticipant.AUTO_BUILD || kind == AbstractBuildParticipant.FULL_BUILD) { final SubMonitor subm = SubMonitor.convert(monitor, Messages.SARLProjectConfigurator_7, NSTEPS); getBuildContext().removeMessages(getMavenProjectFacade().getPomFile()); subm.worked(1); validateSARLCompilerPlugin(); subm.worked(2); if (!this.isEclipsePlugin) { validateSARLLibraryVersion(); } subm.worked(3); validateSARLDependenciesVersions(subm.newChild(1)); subm.worked(NSTEPS); } return null; } private Bundle validateSARLVersion(String groupId, String artifactId, String artifactVersion) { final Bundle bundle = Platform.getBundle(SARL_LANG_BUNDLE_NAME); if (bundle == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_0, SARL_LANG_BUNDLE_NAME), BuildContext.SEVERITY_ERROR, null); return bundle; } final Version bundleVersion = bundle.getVersion(); if (bundleVersion == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_1, SARL_LANG_BUNDLE_NAME), BuildContext.SEVERITY_ERROR, null); return bundle; } final Version minVersion = new Version(bundleVersion.getMajor(), bundleVersion.getMinor(), 0); final Version maxVersion = new Version(bundleVersion.getMajor(), bundleVersion.getMinor() + 1, 0); assert minVersion != null && maxVersion != null; final Version mvnVersion = M2EUtilities.parseMavenVersion(artifactVersion); final int compare = Utilities.compareVersionToRange(mvnVersion, minVersion, maxVersion); if (compare < 0) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_2, groupId, artifactId, artifactVersion, minVersion.toString()), BuildContext.SEVERITY_ERROR, null); } else if (compare > 0) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_3, groupId, artifactId, artifactVersion, maxVersion.toString()), BuildContext.SEVERITY_ERROR, null); } return bundle; } /** Validate the version of the SARL library in the dependencies. * * <p>The test works for standard Java or Maven projects. * * <p>Caution: This function should not be called for Eclipse plugins. * * @throws CoreException if internal error occurs. */ protected void validateSARLLibraryVersion() throws CoreException { final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID)); if (artifact != null) { validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion()); } else { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_6, BuildContext.SEVERITY_ERROR, null); } } /** Validate the version of the SARL compiler in the Maven configuration. * * @return the SARL bundle. * @throws CoreException if internal error occurs. */ protected Bundle validateSARLCompilerPlugin() throws CoreException { final Map<String, Artifact> plugins = getMavenProjectFacade().getMavenProject().getPluginArtifactMap(); final Artifact pluginArtifact = plugins.get(ArtifactUtils.versionlessKey(SARL_PLUGIN_GROUP_ID, SARL_PLUGIN_ARTIFACT_ID)); if (pluginArtifact == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_5, BuildContext.SEVERITY_ERROR, null); } else { final String version = pluginArtifact.getVersion(); if (Strings.isNullOrEmpty(version)) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_5, BuildContext.SEVERITY_ERROR, null); } else { return validateSARLVersion( SARL_PLUGIN_GROUP_ID, SARL_PLUGIN_ARTIFACT_ID, version); } } return null; } /** Validate the versions of the libraries that are in the project dependencies have compatible versions * with the specific dependencies of the SARL library. * * <p>The nearest-win strategy of the dependency resolver may select invalid version for artifacts * that are used by the SARL libraries. * * @param monitor the progress monitor. * @throws CoreException if internal error occurs. */ protected void validateSARLDependenciesVersions(IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 3); final Map<String, String> neededArtifactVersions = new TreeMap<>(); final IMavenProjectFacade facade = getMavenProjectFacade(); final DependencyNode root = MavenPlugin.getMavenModelManager().readDependencyTree( facade, facade.getMavenProject(), Artifact.SCOPE_COMPILE, subm.newChild(1)); final DependencyNode[] sarlNode = new DependencyNode[] {null}; root.accept(new DependencyVisitor() { @Override public boolean visitLeave(DependencyNode node) { if (sarlNode[0] == null && node.getDependency() != null && Objects.equals(node.getDependency().getArtifact().getGroupId(), SARL_MAVENLIB_GROUP_ID) && Objects.equals(node.getDependency().getArtifact().getArtifactId(), SARL_MAVENLIB_ARTIFACT_ID)) { sarlNode[0] = node; return false; } return true; } @Override public boolean visitEnter(DependencyNode node) { return sarlNode[0] == null; } }); subm.worked(1); if (sarlNode[0] != null) { sarlNode[0].accept(new DependencyVisitor() { @Override public boolean visitLeave(DependencyNode node) { if (node.getDependency() != null) { final String grId = node.getDependency().getArtifact().getGroupId(); final String arId = node.getDependency().getArtifact().getArtifactId(); final String key = ArtifactUtils.versionlessKey(grId, arId); final String vers = neededArtifactVersions.get(key); if (vers == null || M2EUtilities.compareMavenVersions(vers, node.getVersion().toString()) < 0) { neededArtifactVersions.put(key, node.getVersion().toString()); } } return true; } @Override public boolean visitEnter(DependencyNode node) { return true; } }); } subm.worked(2); final SubMonitor subm2 = SubMonitor.convert(subm, neededArtifactVersions.size()); int i = 0; final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); for (final Entry<String, String> neededDependency : neededArtifactVersions.entrySet()) { final Artifact artifact = artifacts.get(neededDependency.getKey()); if (artifact != null) { final int cmp = M2EUtilities.compareMavenVersions(neededDependency.getValue(), artifact.getVersion()); if (cmp > 1) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format( Messages.SARLProjectConfigurator_8, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), neededDependency.getValue()), BuildContext.SEVERITY_ERROR, null); } } subm2.worked(i); ++i; } subm.worked(3); } } }
main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/config/SARLProjectConfigurator.java
/* * $Id$ * * SARL is an general-purpose agent programming language. * More details on http://www.sarl.io * * Copyright (C) 2014-2020 the original authors or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.sarl.m2e.config; import java.io.File; import java.text.MessageFormat; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.TreeMap; import com.google.common.base.Strings; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.IClasspathAttribute; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.internal.M2EUtils; import org.eclipse.m2e.core.lifecyclemapping.model.IPluginExecutionMetadata; import org.eclipse.m2e.core.project.IMavenProjectFacade; import org.eclipse.m2e.core.project.MavenProjectUtils; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant; import org.eclipse.m2e.core.project.configurator.AbstractBuildParticipant2; import org.eclipse.m2e.core.project.configurator.AbstractProjectConfigurator; import org.eclipse.m2e.core.project.configurator.ProjectConfigurationRequest; import org.eclipse.m2e.jdt.IClasspathDescriptor; import org.eclipse.m2e.jdt.IClasspathEntryDescriptor; import org.eclipse.m2e.jdt.IJavaProjectConfigurator; import org.eclipse.m2e.jdt.internal.ClasspathDescriptor; import org.osgi.framework.Bundle; import org.osgi.framework.Version; import org.sonatype.plexus.build.incremental.BuildContext; import io.sarl.eclipse.SARLEclipseConfig; import io.sarl.eclipse.buildpath.SARLClasspathContainerInitializer; import io.sarl.eclipse.util.Utilities; import io.sarl.lang.SARLConfig; import io.sarl.lang.SARLVersion; import io.sarl.lang.ui.preferences.SARLPreferences; import io.sarl.m2e.utils.M2EUtilities; /** Project configuration for the M2E. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ public class SARLProjectConfigurator extends AbstractProjectConfigurator implements IJavaProjectConfigurator { private static final String SARL_LANG_BUNDLE_NAME = "io.sarl.lang.core"; //$NON-NLS-1$ private static final String SARL_GROUP_ID = "io.sarl.lang"; //$NON-NLS-1$ private static final String SARL_ARTIFACT_ID = "io.sarl.lang.core"; //$NON-NLS-1$ private static final String SARL_MAVENLIB_GROUP_ID = "io.sarl.maven"; //$NON-NLS-1$ private static final String SARL_MAVENLIB_ARTIFACT_ID = "io.sarl.maven.sdk"; //$NON-NLS-1$ private static final String SARL_PLUGIN_GROUP_ID = "io.sarl.maven"; //$NON-NLS-1$ private static final String SARL_PLUGIN_ARTIFACT_ID = "sarl-maven-plugin"; //$NON-NLS-1$ private static final String ECLIPSE_PLUGIN_PACKAGING = "eclipse-plugin"; //$NON-NLS-1$ /** Invoked to add the preferences dedicated to SARL, JRE, etc. * * @param facade the Maven face. * @param config the configuration. * @param addTestFolders indicates if the test folders should be considered. * @param monitor the monitor. * @throws CoreException if cannot add the source folders. */ @SuppressWarnings("static-method") protected void addPreferences( IMavenProjectFacade facade, SARLConfiguration config, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { final IPath outputPath = makeProjectRelativePath(facade, config.getOutput()); final IPath testOutputPath = addTestFolders ? makeProjectRelativePath(facade, config.getTestOutput()) : null; // Set the SARL preferences SARLPreferences.setSpecificSARLConfigurationFor( facade.getProject(), outputPath, testOutputPath); } private static IPath makeFullPath(IMavenProjectFacade facade, File file) { assert file != null; final IProject project = facade.getProject(); final IPath path; if (!file.isAbsolute()) { path = Path.fromOSString(file.getPath()); } else { path = MavenProjectUtils.getProjectRelativePath(project, file.getAbsolutePath()); } return project.getFullPath().append(path); } private static IPath makeProjectRelativePath(IMavenProjectFacade facade, File file) { assert file != null; final IProject project = facade.getProject(); if (!file.isAbsolute()) { return Path.fromOSString(file.getPath()); } return MavenProjectUtils.getProjectRelativePath(project, file.getAbsolutePath()); } private static IFolder ensureFolderExists(IMavenProjectFacade facade, IPath path, boolean derived, IProgressMonitor monitor) throws CoreException { final IFolder folder = facade.getProject().getFolder(path.makeRelativeTo(facade.getProject().getFullPath())); assert folder != null; if (!folder.exists()) { M2EUtils.createFolder(folder, derived || folder.isDerived(), monitor); } return folder; } /** Invoked to add the source folders. * * @param facade the facade of the Maven project. * @param config the configuration. * @param classpath the project classpath. * @param addTestFolders indicate if the test folders must be added into the classpath. * @param monitor the monitor. * @throws CoreException if cannot add the source folders. */ @SuppressWarnings({"checkstyle:magicnumber", "checkstyle:npathcomplexity"}) protected void addSourceFolders( IMavenProjectFacade facade, SARLConfiguration config, IClasspathDescriptor classpath, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { assertHasNature(facade.getProject(), SARLEclipseConfig.NATURE_ID); assertHasNature(facade.getProject(), SARLEclipseConfig.XTEXT_NATURE_ID); assertHasNature(facade.getProject(), JavaCore.NATURE_ID); final String encoding = config.getEncoding(); final SubMonitor subMonitor = SubMonitor.convert(monitor, 4); // // Add the source folders // // Input folder, e.g. "src/main/sarl" final IPath inputPath = makeFullPath(facade, config.getInput()); final IFolder inputFolder = ensureFolderExists(facade, inputPath, false, subMonitor); if (encoding != null && inputFolder != null && inputFolder.exists()) { inputFolder.setDefaultCharset(encoding, monitor); } IClasspathEntryDescriptor descriptor = classpath.addSourceEntry( inputPath, facade.getOutputLocation(), false); descriptor.setPomDerived(true); subMonitor.worked(1); // Input folder, e.g. "src/main/generated-sources/sarl" final IPath outputPath = makeFullPath(facade, config.getOutput()); final IFolder outputFolder = ensureFolderExists(facade, outputPath, true, subMonitor); if (encoding != null && outputFolder != null && outputFolder.exists()) { outputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( outputPath, facade.getOutputLocation(), false); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, Boolean.TRUE.toString()); subMonitor.worked(1); if (addTestFolders) { // Test input folder, e.g. "src/test/sarl" final IPath testInputPath = makeFullPath(facade, config.getTestInput()); final IFolder testInputFolder = ensureFolderExists(facade, testInputPath, false, subMonitor); if (encoding != null && testInputFolder != null && testInputFolder.exists()) { testInputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( testInputPath, facade.getTestOutputLocation(), true); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.TEST, Boolean.TRUE.toString()); } subMonitor.worked(1); if (addTestFolders) { // Test input folder, e.g. "src/test/generated-sources/sarl" final IPath testOutputPath = makeFullPath(facade, config.getTestOutput()); final IFolder testOutputFolder = ensureFolderExists(facade, testOutputPath, true, subMonitor); if (encoding != null && testOutputFolder != null && testOutputFolder.exists()) { testOutputFolder.setDefaultCharset(encoding, monitor); } descriptor = classpath.addSourceEntry( testOutputPath, facade.getTestOutputLocation(), true); descriptor.setPomDerived(true); descriptor.setClasspathAttribute(IClasspathAttribute.IGNORE_OPTIONAL_PROBLEMS, Boolean.TRUE.toString()); descriptor.setClasspathAttribute(IClasspathAttribute.TEST, Boolean.TRUE.toString()); } subMonitor.done(); } /** Replies the configuration value. * * @param <T> - the expected type. * @param project the project. * @param parameter the parameter name. * @param asType the expected type. * @param mojoExecution the mojo execution. * @param monitor the monitor. * @param defaultValue the default value. * @return the value of the parameter. * @throws CoreException if cannot read the value. */ protected <T> T getParameterValue(MavenProject project, String parameter, Class<T> asType, MojoExecution mojoExecution, IProgressMonitor monitor, T defaultValue) throws CoreException { T value = getParameterValue(project, parameter, asType, mojoExecution, monitor); if (value == null) { value = defaultValue; } return value; } /** Read the SARL configuration. * * @param request the configuration request. * @param monitor the monitor. * @return the SARL configuration. * @throws CoreException if something wrong appends. */ protected SARLConfiguration readConfiguration(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { SARLConfiguration initConfig = null; SARLConfiguration compileConfig = null; final List<MojoExecution> mojos = getMojoExecutions(request, monitor); for (final MojoExecution mojo : mojos) { final String goal = mojo.getGoal(); switch (goal) { case "initialize": //$NON-NLS-1$ initConfig = readInitializeConfiguration(request, mojo, monitor); break; case "compile": //$NON-NLS-1$ case "testCompile": //$NON-NLS-1$ compileConfig = readCompileConfiguration(request, mojo, monitor); break; default: } } if (compileConfig != null && initConfig != null) { compileConfig.setFrom(initConfig); } return compileConfig; } /** Read the configuration for the Initialize mojo. * * @param request the request. * @param mojo the mojo execution. * @param monitor the monitor. * @return the configuration. * @throws CoreException error in the eCore configuration. */ private SARLConfiguration readInitializeConfiguration( ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor) throws CoreException { final SARLConfiguration config = new SARLConfiguration(); final MavenProject project = request.getMavenProject(); final File input = getParameterValue(project, "input", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_SOURCE_SARL)); final File output = getParameterValue(project, "output", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_SOURCE_GENERATED)); final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_BIN)); final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_SOURCE_SARL)); final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_SOURCE_GENERATED)); final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor, //$NON-NLS-1$ new File(SARLConfig.FOLDER_TEST_BIN)); config.setInput(input); config.setOutput(output); config.setBinOutput(binOutput); config.setTestInput(testInput); config.setTestOutput(testOutput); config.setTestBinOutput(testBinOutput); return config; } /** Read the configuration for the Compilation mojo. * * @param request the request. * @param mojo the mojo execution. * @param monitor the monitor. * @return the configuration. * @throws CoreException error in the eCore configuration. */ private SARLConfiguration readCompileConfiguration( ProjectConfigurationRequest request, MojoExecution mojo, IProgressMonitor monitor) throws CoreException { final SARLConfiguration config = new SARLConfiguration(); final MavenProject project = request.getMavenProject(); final File input = getParameterValue(project, "input", File.class, mojo, monitor); //$NON-NLS-1$ final File output = getParameterValue(project, "output", File.class, mojo, monitor); //$NON-NLS-1$ final File binOutput = getParameterValue(project, "binOutput", File.class, mojo, monitor); //$NON-NLS-1$ final File testInput = getParameterValue(project, "testInput", File.class, mojo, monitor); //$NON-NLS-1$ final File testOutput = getParameterValue(project, "testOutput", File.class, mojo, monitor); //$NON-NLS-1$ final File testBinOutput = getParameterValue(project, "testBinOutput", File.class, mojo, monitor); //$NON-NLS-1$ config.setInput(input); config.setOutput(output); config.setBinOutput(binOutput); config.setTestInput(testInput); config.setTestOutput(testOutput); config.setTestBinOutput(testBinOutput); final String inputCompliance = getParameterValue(project, "source", String.class, mojo, monitor); //$NON-NLS-1$ final String outputCompliance = getParameterValue(project, "target", String.class, mojo, monitor); //$NON-NLS-1$ config.setInputCompliance(inputCompliance); config.setOutputCompliance(outputCompliance); final String encoding = getParameterValue(project, "encoding", String.class, mojo, monitor); //$NON-NLS-1$ config.setEncoding(encoding); return config; } /** Remove any reference to the SARL libraries from the given classpath. * * @param classpath the classpath to update. */ @SuppressWarnings("static-method") protected void removeSarlLibraries(IClasspathDescriptor classpath) { classpath.removeEntry(SARLClasspathContainerInitializer.CONTAINER_ID); } /** Add the SARL libraries into the given classpath. * * @param classpath the classpath to update. */ @SuppressWarnings("static-method") protected void addSarlLibraries(IClasspathDescriptor classpath) { final IClasspathEntry entry = JavaCore.newContainerEntry(SARLClasspathContainerInitializer.CONTAINER_ID); classpath.addEntry(entry); } private static void setVersion(Properties props, String propName, String value, String minValue, String incompatibleValue) { final String currentVersion = props.getProperty(propName); String newVersion = value; if (M2EUtilities.compareOsgiVersions(currentVersion, newVersion) > 0) { newVersion = currentVersion; } if (M2EUtilities.compareOsgiVersions(newVersion, minValue) < 0) { props.setProperty(propName, minValue); } else if (M2EUtilities.compareOsgiVersions(newVersion, incompatibleValue) >= 0) { props.setProperty(propName, M2EUtilities.getPreviousOsgiVersion(incompatibleValue)); } else { props.setProperty(propName, newVersion); } } private static void forceMavenCompilerConfiguration(IMavenProjectFacade facade, SARLConfiguration config) { final Properties props = facade.getMavenProject().getProperties(); setVersion(props, "maven.compiler.source", config.getInputCompliance(), //$NON-NLS-1$ SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT, SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT); setVersion(props, "maven.compiler.target", config.getOutputCompliance(), //$NON-NLS-1$ SARLVersion.MINIMAL_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT, SARLVersion.INCOMPATIBLE_JDK_VERSION_FOR_SARL_COMPILATION_ENVIRONMENT); final String encoding = config.getEncoding(); if (encoding != null && !encoding.isEmpty()) { props.setProperty("maven.compiler.encoding", encoding); //$NON-NLS-1$ } } @Override @SuppressWarnings("checkstyle:magicnumber") public void configure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { final IMavenProjectFacade facade = request.getMavenProjectFacade(); // Special case of tycho plugins, for which the {@link #configureRawClasspath} // and {@link #configureClasspath} were not invoked. final boolean isEclipseBundle = ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(facade.getPackaging()); final SubMonitor subMonitor; if (isEclipseBundle) { subMonitor = SubMonitor.convert(monitor, 4); } else { subMonitor = SubMonitor.convert(monitor, 3); } final IProject project = request.getProject(); final SARLConfiguration config = readConfiguration(request, subMonitor.newChild(1)); forceMavenCompilerConfiguration(facade, config); subMonitor.worked(1); io.sarl.eclipse.natures.SARLProjectConfigurator.addSarlNatures( project, subMonitor.newChild(1)); if (isEclipseBundle) { // In the case of Eclipse bundle, the face to the Java project must be created by hand. final IJavaProject javaProject = JavaCore.create(project); final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject); configureSarlProject(facade, config, classpath, false, subMonitor.newChild(1)); subMonitor.worked(1); } } private void configureSarlProject(IMavenProjectFacade facade, SARLConfiguration config, IClasspathDescriptor classpath, boolean addTestFolders, IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 2); addSourceFolders(facade, config, classpath, addTestFolders, subm.newChild(1)); subm.worked(1); addPreferences(facade, config, addTestFolders, subm.newChild(1)); subm.worked(1); } @Override public void unconfigure(ProjectConfigurationRequest request, IProgressMonitor monitor) throws CoreException { final IJavaProject javaProject = JavaCore.create(request.getProject()); final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject); addSarlLibraries(classpath); } @Override public void configureClasspath(IMavenProjectFacade facade, IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException { // } @Override public void configureRawClasspath(ProjectConfigurationRequest request, IClasspathDescriptor classpath, IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 4); final IMavenProjectFacade facade = request.getMavenProjectFacade(); final SARLConfiguration config = readConfiguration(request, subm.newChild(1)); subm.worked(1); removeSarlLibraries(classpath); subm.worked(2); configureSarlProject(facade, config, classpath, true, subm); } @Override public AbstractBuildParticipant getBuildParticipant( IMavenProjectFacade projectFacade, MojoExecution execution, IPluginExecutionMetadata executionMetadata) { return new BuildParticipant(ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(projectFacade.getPackaging())); } /** Build participant for detecting invalid versions of SARL components. * * @author $Author: sgalland$ * @version $FullVersion$ * @mavengroupid $GroupId$ * @mavenartifactid $ArtifactId$ */ protected static class BuildParticipant extends AbstractBuildParticipant2 { private static final int NSTEPS = 4; private final boolean isEclipseBundleProject; /** Construct a build participant. * * @param isEclipseBundleProject indicates if the build participant is created for a Eclipse Bundle project. */ public BuildParticipant(boolean isEclipseBundleProject) { this.isEclipseBundleProject = isEclipseBundleProject; } @Override public Set<IProject> build(int kind, IProgressMonitor monitor) throws Exception { if (kind == AbstractBuildParticipant.AUTO_BUILD || kind == AbstractBuildParticipant.FULL_BUILD) { final SubMonitor subm = SubMonitor.convert(monitor, Messages.SARLProjectConfigurator_7, NSTEPS); getBuildContext().removeMessages(getMavenProjectFacade().getPomFile()); subm.worked(1); validateSARLCompilerPlugin(); subm.worked(2); validateSARLLibraryVersion(); subm.worked(3); validateSARLDependenciesVersions(subm.newChild(1)); subm.worked(NSTEPS); } return null; } private Bundle validateSARLVersion(String groupId, String artifactId, String artifactVersion) { final Bundle bundle = Platform.getBundle(SARL_LANG_BUNDLE_NAME); if (bundle == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_0, SARL_LANG_BUNDLE_NAME), BuildContext.SEVERITY_ERROR, null); return bundle; } final Version bundleVersion = bundle.getVersion(); if (bundleVersion == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_1, SARL_LANG_BUNDLE_NAME), BuildContext.SEVERITY_ERROR, null); return bundle; } final Version minVersion = new Version(bundleVersion.getMajor(), bundleVersion.getMinor(), 0); final Version maxVersion = new Version(bundleVersion.getMajor(), bundleVersion.getMinor() + 1, 0); assert minVersion != null && maxVersion != null; final Version mvnVersion = M2EUtilities.parseMavenVersion(artifactVersion); final int compare = Utilities.compareVersionToRange(mvnVersion, minVersion, maxVersion); if (compare < 0) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_2, groupId, artifactId, artifactVersion, minVersion.toString()), BuildContext.SEVERITY_ERROR, null); } else if (compare > 0) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format(Messages.SARLProjectConfigurator_3, groupId, artifactId, artifactVersion, maxVersion.toString()), BuildContext.SEVERITY_ERROR, null); } return bundle; } /** Validate the version of the SARL library in the dependencies. * * <p>The test works for standard Java or Maven projects, but not for Eclipse bundles. * * @throws CoreException if internal error occurs. */ protected void validateSARLLibraryVersion() throws CoreException { if (!this.isEclipseBundleProject) { final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID)); if (artifact != null) { validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion()); } else { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_6, BuildContext.SEVERITY_ERROR, null); } } } /** Validate the version of the SARL compiler in the Maven configuration. * * @return the SARL bundle. * @throws CoreException if internal error occurs. */ protected Bundle validateSARLCompilerPlugin() throws CoreException { final Map<String, Artifact> plugins = getMavenProjectFacade().getMavenProject().getPluginArtifactMap(); final Artifact pluginArtifact = plugins.get(ArtifactUtils.versionlessKey(SARL_PLUGIN_GROUP_ID, SARL_PLUGIN_ARTIFACT_ID)); if (pluginArtifact == null) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_5, BuildContext.SEVERITY_ERROR, null); } else { final String version = pluginArtifact.getVersion(); if (Strings.isNullOrEmpty(version)) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, Messages.SARLProjectConfigurator_5, BuildContext.SEVERITY_ERROR, null); } else { return validateSARLVersion( SARL_PLUGIN_GROUP_ID, SARL_PLUGIN_ARTIFACT_ID, version); } } return null; } /** Validate the versions of the libraries that are in the project dependencies have compatible versions * with the specific dependencies of the SARL library. * * <p>The nearest-win strategy of the dependency resolver may select invalid version for artifacts * that are used by the SARL libraries. * * @param monitor the progress monitor. * @throws CoreException if internal error occurs. */ protected void validateSARLDependenciesVersions(IProgressMonitor monitor) throws CoreException { final SubMonitor subm = SubMonitor.convert(monitor, 3); final Map<String, String> neededArtifactVersions = new TreeMap<>(); final IMavenProjectFacade facade = getMavenProjectFacade(); final DependencyNode root = MavenPlugin.getMavenModelManager().readDependencyTree( facade, facade.getMavenProject(), Artifact.SCOPE_COMPILE, subm.newChild(1)); final DependencyNode[] sarlNode = new DependencyNode[] {null}; root.accept(new DependencyVisitor() { @Override public boolean visitLeave(DependencyNode node) { if (sarlNode[0] == null && node.getDependency() != null && Objects.equals(node.getDependency().getArtifact().getGroupId(), SARL_MAVENLIB_GROUP_ID) && Objects.equals(node.getDependency().getArtifact().getArtifactId(), SARL_MAVENLIB_ARTIFACT_ID)) { sarlNode[0] = node; return false; } return true; } @Override public boolean visitEnter(DependencyNode node) { return sarlNode[0] == null; } }); subm.worked(1); if (sarlNode[0] != null) { sarlNode[0].accept(new DependencyVisitor() { @Override public boolean visitLeave(DependencyNode node) { if (node.getDependency() != null) { final String grId = node.getDependency().getArtifact().getGroupId(); final String arId = node.getDependency().getArtifact().getArtifactId(); final String key = ArtifactUtils.versionlessKey(grId, arId); final String vers = neededArtifactVersions.get(key); if (vers == null || M2EUtilities.compareMavenVersions(vers, node.getVersion().toString()) < 0) { neededArtifactVersions.put(key, node.getVersion().toString()); } } return true; } @Override public boolean visitEnter(DependencyNode node) { return true; } }); } subm.worked(2); final SubMonitor subm2 = SubMonitor.convert(subm, neededArtifactVersions.size()); int i = 0; final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); for (final Entry<String, String> neededDependency : neededArtifactVersions.entrySet()) { final Artifact artifact = artifacts.get(neededDependency.getKey()); if (artifact != null) { final int cmp = M2EUtilities.compareMavenVersions(neededDependency.getValue(), artifact.getVersion()); if (cmp > 1) { getBuildContext().addMessage( getMavenProjectFacade().getPomFile(), -1, -1, MessageFormat.format( Messages.SARLProjectConfigurator_8, artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), neededDependency.getValue()), BuildContext.SEVERITY_ERROR, null); } } subm2.worked(i); ++i; } subm.worked(3); } } }
[m2e] Change the Eclipse plugin configuration sequence. see #979 Signed-off-by: Stéphane Galland <[email protected]>
main/coreplugins/io.sarl.m2e/src/io/sarl/m2e/config/SARLProjectConfigurator.java
[m2e] Change the Eclipse plugin configuration sequence.
<ide><path>ain/coreplugins/io.sarl.m2e/src/io/sarl/m2e/config/SARLProjectConfigurator.java <ide> } <ide> } <ide> <add> /** Replies if the given project facade is pointing an Eclipe plugin. <add> * <add> * @param facade the maven project facade. <add> * @return {@code true} if the facade is for an Eclipse plugin. <add> * @since 0.11 <add> */ <add> public boolean isEclipsePluginPackaging(IMavenProjectFacade facade) { <add> return ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(facade.getPackaging()); <add> } <add> <ide> @Override <ide> @SuppressWarnings("checkstyle:magicnumber") <ide> public void configure(ProjectConfigurationRequest request, <ide> IProgressMonitor monitor) throws CoreException { <ide> final IMavenProjectFacade facade = request.getMavenProjectFacade(); <ide> <add> // --- ECLIPSE PLUGIN --------------------------------------------------------------- <ide> // Special case of tycho plugins, for which the {@link #configureRawClasspath} <ide> // and {@link #configureClasspath} were not invoked. <del> final boolean isEclipseBundle = ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(facade.getPackaging()); <add> // ---------------------------------------------------------------------------------- <add> final boolean isEclipsePlugin = isEclipsePluginPackaging(facade); <ide> <ide> final SubMonitor subMonitor; <del> if (isEclipseBundle) { <add> if (isEclipsePlugin) { <ide> subMonitor = SubMonitor.convert(monitor, 4); <ide> } else { <ide> subMonitor = SubMonitor.convert(monitor, 3); <ide> final IProject project = request.getProject(); <ide> <ide> final SARLConfiguration config = readConfiguration(request, subMonitor.newChild(1)); <add> subMonitor.worked(1); <ide> forceMavenCompilerConfiguration(facade, config); <ide> subMonitor.worked(1); <del> io.sarl.eclipse.natures.SARLProjectConfigurator.addSarlNatures( <del> project, <del> subMonitor.newChild(1)); <del> <del> if (isEclipseBundle) { <add> <add> // --- ECLIPSE PLUGIN --------------------------------------------------------------- <add> if (isEclipsePlugin) { <ide> // In the case of Eclipse bundle, the face to the Java project must be created by hand. <ide> final IJavaProject javaProject = JavaCore.create(project); <ide> final IClasspathDescriptor classpath = new ClasspathDescriptor(javaProject); <ide> configureSarlProject(facade, config, classpath, false, subMonitor.newChild(1)); <ide> subMonitor.worked(1); <ide> } <add> // ---------------------------------------------------------------------------------- <add> <add> io.sarl.eclipse.natures.SARLProjectConfigurator.addSarlNatures( <add> project, <add> subMonitor.newChild(1)); <add> subMonitor.worked(1); <ide> } <ide> <ide> private void configureSarlProject(IMavenProjectFacade facade, SARLConfiguration config, <ide> public AbstractBuildParticipant getBuildParticipant( <ide> IMavenProjectFacade projectFacade, MojoExecution execution, <ide> IPluginExecutionMetadata executionMetadata) { <del> return new BuildParticipant(ECLIPSE_PLUGIN_PACKAGING.equalsIgnoreCase(projectFacade.getPackaging())); <add> return new BuildParticipant(isEclipsePluginPackaging(projectFacade)); <ide> } <ide> <ide> /** Build participant for detecting invalid versions of SARL components. <ide> <ide> private static final int NSTEPS = 4; <ide> <del> private final boolean isEclipseBundleProject; <add> private final boolean isEclipsePlugin; <ide> <ide> /** Construct a build participant. <ide> * <del> * @param isEclipseBundleProject indicates if the build participant is created for a Eclipse Bundle project. <add> * @param isEclipsePlugin indicates if the build participant is created for an Eclipse plugin project. <ide> */ <del> public BuildParticipant(boolean isEclipseBundleProject) { <del> this.isEclipseBundleProject = isEclipseBundleProject; <add> public BuildParticipant(boolean isEclipsePlugin) { <add> this.isEclipsePlugin = isEclipsePlugin; <ide> } <ide> <ide> @Override <ide> subm.worked(1); <ide> validateSARLCompilerPlugin(); <ide> subm.worked(2); <del> validateSARLLibraryVersion(); <add> if (!this.isEclipsePlugin) { <add> validateSARLLibraryVersion(); <add> } <ide> subm.worked(3); <ide> validateSARLDependenciesVersions(subm.newChild(1)); <ide> subm.worked(NSTEPS); <ide> <ide> /** Validate the version of the SARL library in the dependencies. <ide> * <del> * <p>The test works for standard Java or Maven projects, but not for Eclipse bundles. <add> * <p>The test works for standard Java or Maven projects. <add> * <add> * <p>Caution: This function should not be called for Eclipse plugins. <ide> * <ide> * @throws CoreException if internal error occurs. <ide> */ <ide> protected void validateSARLLibraryVersion() throws CoreException { <del> if (!this.isEclipseBundleProject) { <del> final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); <del> final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID)); <del> if (artifact != null) { <del> validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion()); <del> } else { <del> getBuildContext().addMessage( <del> getMavenProjectFacade().getPomFile(), <del> -1, -1, <del> Messages.SARLProjectConfigurator_6, <del> BuildContext.SEVERITY_ERROR, <del> null); <del> } <add> final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap(); <add> final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID)); <add> if (artifact != null) { <add> validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion()); <add> } else { <add> getBuildContext().addMessage( <add> getMavenProjectFacade().getPomFile(), <add> -1, -1, <add> Messages.SARLProjectConfigurator_6, <add> BuildContext.SEVERITY_ERROR, <add> null); <ide> } <ide> } <ide>
JavaScript
apache-2.0
d777c732613f5c61b5bccf8bd18cedcc65209129
0
weitzj/closure-compiler,weitzj/closure-compiler
/* * Copyright 2011 PicNet Pty Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Definitions for W3C's IndexedDB API. In Chrome all the * IndexedDB classes are prefixed with 'webkit'. In order to access constants * and static methods of these classes they must be duplicated with the * prefix here. * @see http://www.w3.org/TR/IndexedDB/ * * @externs * @author [email protected] (Guido Tapia) */ /** @type {IDBFactory} */ Window.prototype.moz_indexedDB; /** @type {IDBFactory} */ Window.prototype.mozIndexedDB; /** @type {IDBFactory} */ Window.prototype.webkitIndexedDB; /** @type {IDBFactory} */ Window.prototype.msIndexedDB; /** @type {IDBFactory} */ Window.prototype.indexedDB; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBFactory */ function IDBFactory() {} /** * @param {string} name The name of the database to open. * @param {number=} opt_version The version at which to open the database. * @return {!IDBOpenDBRequest} The IDBRequest object. */ IDBFactory.prototype.open = function(name, opt_version) {}; /** * @param {string} name The name of the database to delete. * @return {!IDBOpenDBRequest} The IDBRequest object. */ IDBFactory.prototype.deleteDatabase = function(name) {}; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException */ function IDBDatabaseException() {} /** * @constructor * @extends {IDBDatabaseException} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException */ function webkitIDBDatabaseException() {} /** * @const * @type {number} */ IDBDatabaseException.UNKNOWN_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.UNKNOWN_ERR; /** * @const * @type {number} */ IDBDatabaseException.NON_TRANSIENT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NON_TRANSIENT_ERR; /** * @const * @type {number} */ IDBDatabaseException.NOT_FOUND_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NOT_FOUND_ERR; /** * @const * @type {number} */ IDBDatabaseException.CONSTRAINT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.CONSTRAINT_ERR; /** * @const * @type {number} */ IDBDatabaseException.DATA_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.DATA_ERR; /** * @const * @type {number} */ IDBDatabaseException.NOT_ALLOWED_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NOT_ALLOWED_ERR; /** * @const * @type {number} */ IDBDatabaseException.TRANSACTION_INACTIVE_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.TRANSACTION_INACTIVE_ERR; /** * @const * @type {number} */ IDBDatabaseException.ABORT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.ABORT_ERR; /** * @const * @type {number} */ IDBDatabaseException.READ_ONLY_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.READ_ONLY_ERR; /** * @const * @type {number} */ IDBDatabaseException.TIMEOUT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.TIMEOUT_ERR; /** * @const * @type {number} */ IDBDatabaseException.QUOTA_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.QUOTA_ERR; /** * @const * @type {number} */ IDBDatabaseException.code; /** * @const * @type {number} */ webkitIDBDatabaseException.code; /** * @const * @type {string} */ IDBDatabaseException.message; /** * @const * @type {string} */ webkitIDBDatabaseException.message; /** @type {function(new:IDBRequest)} */ Window.prototype.IDBRequest; /** @type {function(new:IDBRequest)} */ Window.prototype.webkitIDBRequest; /** * @constructor * @implements {EventTarget} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBRequest */ function IDBRequest() {} /** @override */ IDBRequest.prototype.addEventListener = function(type, listener, useCapture) {}; /** @override */ IDBRequest.prototype.removeEventListener = function(type, listener, useCapture) {}; /** @override */ IDBRequest.prototype.dispatchEvent = function(evt) {}; /** * @constructor * @extends {IDBRequest} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBRequest */ function webkitIDBRequest() {} /** * @type {number} * @const */ IDBRequest.LOADING; /** * @type {number} * @const */ webkitIDBRequest.LOADING; /** * @type {number} * @const */ IDBRequest.DONE; /** * @type {number} * @const */ webkitIDBRequest.DONE; /** * @type {number} * @const */ IDBRequest.prototype.readyState; /** * @type {function(!Event)} */ IDBRequest.prototype.onsuccess = function(e) {}; /** * @type {function(!Event)} */ IDBRequest.prototype.onerror = function(e) {}; /** * @type {*} * @const */ IDBRequest.prototype.result; /** * @type {number} * @const */ IDBRequest.prototype.errorCode; /** * @type {Object} * @const */ IDBRequest.prototype.source; /** * @type {IDBTransaction} * @const */ IDBRequest.prototype.transaction; /** @type {function(new:IDBOpenDBRequest)} */ Window.prototype.IDBOpenDBRequest; /** * @constructor * @extends {IDBRequest} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBOpenDBRequest */ function IDBOpenDBRequest() {} /** * @type {function(!IDBVersionChangeEvent)} */ IDBOpenDBRequest.prototype.onblocked = function(e) {}; /** * @type {function(!IDBVersionChangeEvent)} */ IDBOpenDBRequest.prototype.onupgradeneeded = function(e) {}; /** * @constructor * @implements {EventTarget} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabase */ function IDBDatabase() {} /** * @type {string} * @const */ IDBDatabase.prototype.name; /** * @type {string} * @const */ IDBDatabase.prototype.description; /** * @type {string} * @const */ IDBDatabase.prototype.version; /** * @type {DOMStringList} * @const */ IDBDatabase.prototype.objectStoreNames; /** * @param {string} name The name of the object store. * @param {Object=} opt_parameters Parameters to be passed * creating the object store. * @return {!IDBObjectStore} The created/open object store. */ IDBDatabase.prototype.createObjectStore = function(name, opt_parameters) {}; /** * @param {string} name The name of the object store to remove. */ IDBDatabase.prototype.deleteObjectStore = function(name) {}; /** * @param {string} version The new version of the database. * @return {!IDBRequest} The IDBRequest object. */ IDBDatabase.prototype.setVersion = function(version) {}; /** * @param {Array.<string>} storeNames The stores to open in this transaction. * @param {(number|string)=} mode The mode for opening the object stores. * @return {!IDBTransaction} The IDBRequest object. */ IDBDatabase.prototype.transaction = function(storeNames, mode) {}; /** * Closes the database connection. */ IDBDatabase.prototype.close = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onabort = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onerror = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onversionchange = function() {}; /** @override */ IDBDatabase.prototype.addEventListener = function(type, listener, useCapture) {}; /** @override */ IDBDatabase.prototype.removeEventListener = function(type, listener, useCapture) {}; /** @override */ IDBDatabase.prototype.dispatchEvent = function(evt) {}; /** * Typedef for valid key types according to the w3 specification. Note that this * is slightly wider than what is actually allowed, as all Array elements must * have a valid key type. * @see http://www.w3.org/TR/IndexedDB/#key-construct * @typedef {number|string|!Date|!Array} */ var IDBKeyType; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBObjectStore */ function IDBObjectStore() {} /** * @type {string} */ IDBObjectStore.prototype.name; /** * @type {string} */ IDBObjectStore.prototype.keyPath; /** * @type {DOMStringList} */ IDBObjectStore.prototype.indexNames; /** @type {IDBTransaction} */ IDBObjectStore.prototype.transaction; /** @type {boolean} */ IDBObjectStore.prototype.autoIncrement; /** * @param {*} value The value to put into the object store. * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.put = function(value, key) {}; /** * @param {*} value The value to add into the object store. * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.add = function(value, key) {}; /** * @param {*} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype['delete'] = function(key) {}; /** * @param {*} key The key of the document to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.get = function(key) {}; /** * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.clear = function() {}; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.openCursor = function(range, direction) {}; /** * @param {string} name The name of the index. * @param {string} keyPath The path to the index key. * @param {Object=} opt_paramters Optional parameters * for the created index. * @return {!IDBIndex} The IDBIndex object. */ IDBObjectStore.prototype.createIndex = function(name, keyPath, opt_paramters) {}; /** * @param {string} name The name of the index to retrieve. * @return {!IDBIndex} The IDBIndex object. */ IDBObjectStore.prototype.index = function(name) {}; /** * @param {string} indexName The name of the index to remove. */ IDBObjectStore.prototype.deleteIndex = function(indexName) {}; /** * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.count = function(key) {}; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex */ function IDBIndex() {} /** * @type {string} * @const */ IDBIndex.prototype.name; /** * @type {!IDBObjectStore} * @const */ IDBIndex.prototype.objectStore; /** * @type {string} * @const */ IDBIndex.prototype.keyPath; /** * @type {boolean} * @const */ IDBIndex.prototype.unique; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.openCursor = function(range, direction) {}; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.openKeyCursor = function(range, direction) {}; /** * @param {*} key The id of the object to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.get = function(key) {}; /** * @param {*} key The id of the object to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.getKey = function(key) {}; /** @type {function(new:IDBCursor)} */ Window.prototype.IDBCursor; /** @type {function(new:IDBCursor)} */ Window.prototype.webkitIDBCursor; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBCursor */ function IDBCursor() {} /** * @constructor * @extends {IDBCursor} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBCursor */ function webkitIDBCursor() {} /** * @const * @type {number} */ IDBCursor.NEXT; /** * @const * @type {number} */ webkitIDBCursor.NEXT; /** * @const * @type {number} */ IDBCursor.NEXT_NO_DUPLICATE; /** * @const * @type {number} */ webkitIDBCursor.NEXT_NO_DUPLICATE; /** * @const * @type {number} */ IDBCursor.PREV; /** * @const * @type {number} */ webkitIDBCursor.PREV; /** * @const * @type {number} */ IDBCursor.PREV_NO_DUPLICATE; /** * @const * @type {number} */ webkitIDBCursor.PREV_NO_DUPLICATE; /** * @type {*} * @const */ IDBCursor.prototype.source; /** * @type {number} * @const */ IDBCursor.prototype.direction; /** * @type {IDBKeyType} * @const */ IDBCursor.prototype.key; /** * @type {number} * @const */ IDBCursor.prototype.primaryKey; /** * @param {*} value The new value for the current object in the cursor. * @return {!IDBRequest} The IDBRequest object. */ IDBCursor.prototype.update = function(value) {}; /** * Note: Must be quoted to avoid parse error. * @param {*=} key Continue enumerating the cursor from the specified key * (or next). */ IDBCursor.prototype['continue'] = function(key) {}; /** * @param {number} count Number of times to iterate the cursor. */ IDBCursor.prototype.advance = function(count) {}; /** * Note: Must be quoted to avoid parse error. * @return {!IDBRequest} The IDBRequest object. */ IDBCursor.prototype['delete'] = function() {}; /** @type {function(new:IDBTransaction)} */ Window.prototype.IDBTransaction; /** @type {function(new:IDBTransaction)} */ Window.prototype.webkitIDBTransaction; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBTransaction */ function IDBTransaction() {} /** * @constructor * @extends {IDBTransaction} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBTransaction */ function webkitIDBTransaction() {} /** * @const * @type {number} */ IDBTransaction.READ_WRITE; /** * @const * @type {number} */ webkitIDBTransaction.READ_WRITE; /** * @const * @type {number} */ IDBTransaction.READ_ONLY; /** * @const * @type {number} */ webkitIDBTransaction.READ_ONLY; /** * @const * @type {number} */ IDBTransaction.VERSION_CHANGE; /** * @const * @type {number} */ webkitIDBTransaction.VERSION_CHANGE; /** * @type {number|string} * @const */ IDBTransaction.prototype.mode; /** * @type {IDBDatabase} * @const */ IDBTransaction.prototype.db; /** * @param {string} name The name of the object store to retrieve. * @return {!IDBObjectStore} The object store. */ IDBTransaction.prototype.objectStore = function(name) {}; /** * Aborts the transaction. */ IDBTransaction.prototype.abort = function() {}; /** * @type {Function} */ IDBTransaction.prototype.onabort = function() {}; /** * @type {Function} */ IDBTransaction.prototype.oncomplete = function() {}; /** * @type {Function} */ IDBTransaction.prototype.onerror = function() {}; /** @type {function(new:IDBKeyRange)} */ Window.prototype.IDBKeyRange; /** @type {function(new:IDBKeyRange)} */ Window.prototype.webkitIDBKeyRange; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBKeyRange */ function IDBKeyRange() {} /** * @constructor * @extends {IDBKeyRange} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBKeyRange */ function webkitIDBKeyRange() {} /** * @type {*} * @const */ IDBKeyRange.prototype.lower; /** * @type {*} * @const */ IDBKeyRange.prototype.upper; /** * @type {*} * @const */ IDBKeyRange.prototype.lowerOpen; /** * @type {*} * @const */ IDBKeyRange.prototype.upperOpen; /** * @param {*} value The single key value of this range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.only = function(value) {}; /** * @param {*} value The single key value of this range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.only = function(value) {}; /** * @param {*} bound Creates a lower bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.lowerBound = function(bound, open) {}; /** * @param {*} bound Creates a lower bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.lowerBound = function(bound, open) {}; /** * @param {*} bound Creates an upper bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.upperBound = function(bound, open) {}; /** * @param {*} bound Creates an upper bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.upperBound = function(bound, open) {}; /** * @param {*} left The left bound value of openLeft is true. * @param {*} right The right bound value of openRight is true. * @param {boolean=} openLeft Whether to open a left bound range. * @param {boolean=} openRight Whether to open a right bound range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.bound = function(left, right, openLeft, openRight) {}; /** * @param {*} left The left bound value of openLeft is true. * @param {*} right The right bound value of openRight is true. * @param {boolean=} openLeft Whether to open a left bound range. * @param {boolean=} openRight Whether to open a right bound range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.bound = function(left, right, openLeft, openRight) {}; /** * @constructor * @extends {Event} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBVersionChangeEvent */ function IDBVersionChangeEvent() {} /** * @type {number} * @const */ IDBVersionChangeEvent.prototype.oldVersion; /** * @type {?number} * @const */ IDBVersionChangeEvent.prototype.newVersion; /** * @constructor * @extends {IDBVersionChangeEvent} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBVersionChangeEvent */ function webkitIDBVersionChangeEvent() {} /** * @type {string} * @const */ webkitIDBVersionChangeEvent.prototype.version;
externs/w3c_indexeddb.js
/* * Copyright 2011 PicNet Pty Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Definitions for W3C's IndexedDB API. In Chrome all the * IndexedDB classes are prefixed with 'webkit'. In order to access constants * and static methods of these classes they must be duplicated with the * prefix here. * @see http://www.w3.org/TR/IndexedDB/ * * @externs * @author [email protected] (Guido Tapia) */ /** @type {IDBFactory} */ Window.prototype.moz_indexedDB; /** @type {IDBFactory} */ Window.prototype.mozIndexedDB; /** @type {IDBFactory} */ Window.prototype.webkitIndexedDB; /** @type {IDBFactory} */ Window.prototype.msIndexedDB; /** @type {IDBFactory} */ Window.prototype.indexedDB; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBFactory */ function IDBFactory() {} /** * @param {string} name The name of the database to open. * @param {number=} opt_version The version at which to open the database. * @return {!IDBOpenDBRequest} The IDBRequest object. */ IDBFactory.prototype.open = function(name, opt_version) {}; /** * @param {string} name The name of the database to delete. * @return {!IDBOpenDBRequest} The IDBRequest object. */ IDBFactory.prototype.deleteDatabase = function(name) {}; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException */ function IDBDatabaseException() {} /** * @constructor * @extends {IDBDatabaseException} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException */ function webkitIDBDatabaseException() {} /** * @const * @type {number} */ IDBDatabaseException.UNKNOWN_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.UNKNOWN_ERR; /** * @const * @type {number} */ IDBDatabaseException.NON_TRANSIENT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NON_TRANSIENT_ERR; /** * @const * @type {number} */ IDBDatabaseException.NOT_FOUND_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NOT_FOUND_ERR; /** * @const * @type {number} */ IDBDatabaseException.CONSTRAINT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.CONSTRAINT_ERR; /** * @const * @type {number} */ IDBDatabaseException.DATA_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.DATA_ERR; /** * @const * @type {number} */ IDBDatabaseException.NOT_ALLOWED_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.NOT_ALLOWED_ERR; /** * @const * @type {number} */ IDBDatabaseException.TRANSACTION_INACTIVE_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.TRANSACTION_INACTIVE_ERR; /** * @const * @type {number} */ IDBDatabaseException.ABORT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.ABORT_ERR; /** * @const * @type {number} */ IDBDatabaseException.READ_ONLY_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.READ_ONLY_ERR; /** * @const * @type {number} */ IDBDatabaseException.TIMEOUT_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.TIMEOUT_ERR; /** * @const * @type {number} */ IDBDatabaseException.QUOTA_ERR; /** * @const * @type {number} */ webkitIDBDatabaseException.QUOTA_ERR; /** * @const * @type {number} */ IDBDatabaseException.code; /** * @const * @type {number} */ webkitIDBDatabaseException.code; /** * @const * @type {string} */ IDBDatabaseException.message; /** * @const * @type {string} */ webkitIDBDatabaseException.message; /** @type {function(new:IDBRequest)} */ Window.prototype.IDBRequest; /** @type {function(new:IDBRequest)} */ Window.prototype.webkitIDBRequest; /** * @constructor * @implements {EventTarget} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBRequest */ function IDBRequest() {} /** @override */ IDBRequest.prototype.addEventListener = function(type, listener, useCapture) {}; /** @override */ IDBRequest.prototype.removeEventListener = function(type, listener, useCapture) {}; /** @override */ IDBRequest.prototype.dispatchEvent = function(evt) {}; /** * @constructor * @extends {IDBRequest} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBRequest */ function webkitIDBRequest() {} /** * @type {number} * @const */ IDBRequest.LOADING; /** * @type {number} * @const */ webkitIDBRequest.LOADING; /** * @type {number} * @const */ IDBRequest.DONE; /** * @type {number} * @const */ webkitIDBRequest.DONE; /** * @type {number} * @const */ IDBRequest.prototype.readyState; /** * @type {function(!Event)} */ IDBRequest.prototype.onsuccess = function(e) {}; /** * @type {function(!Event)} */ IDBRequest.prototype.onerror = function(e) {}; /** * @type {*} * @const */ IDBRequest.prototype.result; /** * @type {number} * @const */ IDBRequest.prototype.errorCode; /** * @type {Object} * @const */ IDBRequest.prototype.source; /** * @type {IDBTransaction} * @const */ IDBRequest.prototype.transaction; /** @type {function(new:IDBOpenDBRequest)} */ Window.prototype.IDBOpenDBRequest; /** * @constructor * @extends {IDBRequest} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBOpenDBRequest */ function IDBOpenDBRequest() {} /** * @type {function(!IDBVersionChangeEvent)} */ IDBOpenDBRequest.prototype.onblocked = function(e) {}; /** * @type {function(!IDBVersionChangeEvent)} */ IDBOpenDBRequest.prototype.onupgradeneeded = function(e) {}; /** * @constructor * @implements {EventTarget} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabase */ function IDBDatabase() {} /** * @type {string} * @const */ IDBDatabase.prototype.name; /** * @type {string} * @const */ IDBDatabase.prototype.description; /** * @type {string} * @const */ IDBDatabase.prototype.version; /** * @type {DOMStringList} * @const */ IDBDatabase.prototype.objectStoreNames; /** * @param {string} name The name of the object store. * @param {Object=} opt_parameters Parameters to be passed * creating the object store. * @return {!IDBObjectStore} The created/open object store. */ IDBDatabase.prototype.createObjectStore = function(name, opt_parameters) {}; /** * @param {string} name The name of the object store to remove. */ IDBDatabase.prototype.deleteObjectStore = function(name) {}; /** * @param {string} version The new version of the database. * @return {!IDBRequest} The IDBRequest object. */ IDBDatabase.prototype.setVersion = function(version) {}; /** * @param {Array.<string>} storeNames The stores to open in this transaction. * @param {(number|string)=} mode The mode for opening the object stores. * @return {!IDBTransaction} The IDBRequest object. */ IDBDatabase.prototype.transaction = function(storeNames, mode) {}; /** * Closes the database connection. */ IDBDatabase.prototype.close = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onabort = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onerror = function() {}; /** * @type {Function} */ IDBDatabase.prototype.onversionchange = function() {}; /** @override */ IDBDatabase.prototype.addEventListener = function(type, listener, useCapture) {}; /** @override */ IDBDatabase.prototype.removeEventListener = function(type, listener, useCapture) {}; /** @override */ IDBDatabase.prototype.dispatchEvent = function(evt) {}; /** * Typedef for valid key types according to the w3 specification. Note that this * is slightly wider than what is actually allowed, as all Array elements must * have a valid key type. * @see http://www.w3.org/TR/IndexedDB/#key-construct * @typedef {number|string|!Date|!Array} */ var IDBKeyType; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBObjectStore */ function IDBObjectStore() {} /** * @type {string} */ IDBObjectStore.prototype.name; /** * @type {string} */ IDBObjectStore.prototype.keyPath; /** * @type {DOMStringList} */ IDBObjectStore.prototype.indexNames; /** @type {IDBTransaction} */ IDBObjectStore.prototype.transaction; /** @type {boolean} */ IDBObjectStore.prototype.autoIncrement; /** * @param {*} value The value to put into the object store. * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.put = function(value, key) {}; /** * @param {*} value The value to add into the object store. * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.add = function(value, key) {}; /** * @param {*} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype['delete'] = function(key) {}; /** * @param {*} key The key of the document to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.get = function(key) {}; /** * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.clear = function() {}; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.openCursor = function(range, direction) {}; /** * @param {string} name The name of the index. * @param {string} keyPath The path to the index key. * @param {Object=} opt_paramters Optional parameters * for the created index. * @return {!IDBIndex} The IDBIndex object. */ IDBObjectStore.prototype.createIndex = function(name, keyPath, opt_paramters) {}; /** * @param {string} name The name of the index to retrieve. * @return {!IDBIndex} The IDBIndex object. */ IDBObjectStore.prototype.index = function(name) {}; /** * @param {string} indexName The name of the index to remove. */ IDBObjectStore.prototype.deleteIndex = function(indexName) {}; /** * @param {*=} key The key of this value. * @return {!IDBRequest} The IDBRequest object. */ IDBObjectStore.prototype.count = function(key) {}; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex */ function IDBIndex() {} /** * @type {string} * @const */ IDBIndex.prototype.name; /** * @type {!IDBObjectStore} * @const */ IDBIndex.prototype.objectStore; /** * @type {string} * @const */ IDBIndex.prototype.keyPath; /** * @type {boolean} * @const */ IDBIndex.prototype.unique; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.openCursor = function(range, direction) {}; /** * @param {IDBKeyRange=} range The range of the cursor. * @param {(number|string)=} direction The direction of cursor enumeration. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.openKeyCursor = function(range, direction) {}; /** * @param {*} key The id of the object to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.get = function(key) {}; /** * @param {*} key The id of the object to retrieve. * @return {!IDBRequest} The IDBRequest object. */ IDBIndex.prototype.getKey = function(key) {}; /** @type {function(new:IDBCursor)} */ Window.prototype.IDBCursor; /** @type {function(new:IDBCursor)} */ Window.prototype.webkitIDBCursor; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBCursor */ function IDBCursor() {} /** * @constructor * @extends {IDBCursor} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBCursor */ function webkitIDBCursor() {} /** * @const * @type {number} */ IDBCursor.NEXT; /** * @const * @type {number} */ webkitIDBCursor.NEXT; /** * @const * @type {number} */ IDBCursor.NEXT_NO_DUPLICATE; /** * @const * @type {number} */ webkitIDBCursor.NEXT_NO_DUPLICATE; /** * @const * @type {number} */ IDBCursor.PREV; /** * @const * @type {number} */ webkitIDBCursor.PREV; /** * @const * @type {number} */ IDBCursor.PREV_NO_DUPLICATE; /** * @const * @type {number} */ webkitIDBCursor.PREV_NO_DUPLICATE; /** * @type {*} * @const */ IDBCursor.prototype.source; /** * @type {number} * @const */ IDBCursor.prototype.direction; /** * @type {IDBKeyType} * @const */ IDBCursor.prototype.key; /** * @type {number} * @const */ IDBCursor.prototype.primaryKey; /** * @param {*} value The new value for the current object in the cursor. * @return {!IDBRequest} The IDBRequest object. */ IDBCursor.prototype.update = function(value) {}; /** * Note: Must be quoted to avoid parse error. * @param {*=} key Continue enumerating the cursor from the specified key * (or next). */ IDBCursor.prototype['continue'] = function(key) {}; /** * @param {number} count Number of times to iterate the cursor. */ IDBCursor.prototype.advance = function(count) {}; /** * Note: Must be quoted to avoid parse error. * @return {!IDBRequest} The IDBRequest object. */ IDBCursor.prototype['delete'] = function() {}; /** @type {function(new:IDBTransaction)} */ Window.prototype.IDBTransaction; /** @type {function(new:IDBTransaction)} */ Window.prototype.webkitIDBTransaction; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBTransaction */ function IDBTransaction() {} /** * @constructor * @extends {IDBTransaction} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBTransaction */ function webkitIDBTransaction() {} /** * @const * @type {number} */ IDBTransaction.READ_WRITE; /** * @const * @type {number} */ webkitIDBTransaction.READ_WRITE; /** * @const * @type {number} */ IDBTransaction.READ_ONLY; /** * @const * @type {number} */ webkitIDBTransaction.READ_ONLY; /** * @const * @type {number} */ IDBTransaction.VERSION_CHANGE; /** * @const * @type {number} */ webkitIDBTransaction.VERSION_CHANGE; /** * @type {number} * @const */ IDBTransaction.prototype.mode; /** * @type {IDBDatabase} * @const */ IDBTransaction.prototype.db; /** * @param {string} name The name of the object store to retrieve. * @return {!IDBObjectStore} The object store. */ IDBTransaction.prototype.objectStore = function(name) {}; /** * Aborts the transaction. */ IDBTransaction.prototype.abort = function() {}; /** * @type {Function} */ IDBTransaction.prototype.onabort = function() {}; /** * @type {Function} */ IDBTransaction.prototype.oncomplete = function() {}; /** * @type {Function} */ IDBTransaction.prototype.onerror = function() {}; /** @type {function(new:IDBKeyRange)} */ Window.prototype.IDBKeyRange; /** @type {function(new:IDBKeyRange)} */ Window.prototype.webkitIDBKeyRange; /** * @constructor * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBKeyRange */ function IDBKeyRange() {} /** * @constructor * @extends {IDBKeyRange} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBKeyRange */ function webkitIDBKeyRange() {} /** * @type {*} * @const */ IDBKeyRange.prototype.lower; /** * @type {*} * @const */ IDBKeyRange.prototype.upper; /** * @type {*} * @const */ IDBKeyRange.prototype.lowerOpen; /** * @type {*} * @const */ IDBKeyRange.prototype.upperOpen; /** * @param {*} value The single key value of this range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.only = function(value) {}; /** * @param {*} value The single key value of this range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.only = function(value) {}; /** * @param {*} bound Creates a lower bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.lowerBound = function(bound, open) {}; /** * @param {*} bound Creates a lower bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.lowerBound = function(bound, open) {}; /** * @param {*} bound Creates an upper bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.upperBound = function(bound, open) {}; /** * @param {*} bound Creates an upper bound key range. * @param {boolean=} open Open the key range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.upperBound = function(bound, open) {}; /** * @param {*} left The left bound value of openLeft is true. * @param {*} right The right bound value of openRight is true. * @param {boolean=} openLeft Whether to open a left bound range. * @param {boolean=} openRight Whether to open a right bound range. * @return {!IDBKeyRange} The key range. */ IDBKeyRange.bound = function(left, right, openLeft, openRight) {}; /** * @param {*} left The left bound value of openLeft is true. * @param {*} right The right bound value of openRight is true. * @param {boolean=} openLeft Whether to open a left bound range. * @param {boolean=} openRight Whether to open a right bound range. * @return {!IDBKeyRange} The key range. */ webkitIDBKeyRange.bound = function(left, right, openLeft, openRight) {}; /** * @constructor * @extends {Event} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBVersionChangeEvent */ function IDBVersionChangeEvent() {} /** * @type {number} * @const */ IDBVersionChangeEvent.prototype.oldVersion; /** * @type {?number} * @const */ IDBVersionChangeEvent.prototype.newVersion; /** * @constructor * @extends {IDBVersionChangeEvent} * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBVersionChangeEvent */ function webkitIDBVersionChangeEvent() {} /** * @type {string} * @const */ webkitIDBVersionChangeEvent.prototype.version;
Update IDBTransaction.prototype.mode to reflect that the spec is changing R=venkatgv DELTA=1 (0 added, 0 deleted, 1 changed) Revision created by MOE tool push_codebase. MOE_MIGRATION=5984 git-svn-id: 818616af560c21f974e3119d89e3310384da871a@2401 b0f006be-c8cd-11de-a2e8-8d36a3108c74
externs/w3c_indexeddb.js
<ide><path>xterns/w3c_indexeddb.js <ide> webkitIDBTransaction.VERSION_CHANGE; <ide> <ide> /** <del> * @type {number} <add> * @type {number|string} <ide> * @const <ide> */ <ide> IDBTransaction.prototype.mode;
Java
apache-2.0
2671dc5fb248b722d5b86ebbabe69dbde5d58dfb
0
geordie3535/Sunshine
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Encapsulates fetching the forecast and displaying it as a {@link ListView} layout. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; //initializing the ArrayAdapter holds Strings public ForecastFragment() { //no-arg constructor , no needed actually but just in case if we want to automate it. } @Override public void onCreate(Bundle savedInstanceState){ //Called when the activity is starting //If the activity is being re-initialized after previously being shut down then this Bundle //contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null. super.onCreate(savedInstanceState); //Derived classes must call through to the super class's implementation of this method //Added this line in order for this fragment to handle menu events. setHasOptionsMenu(true); //Report that this fragment would like to participate in populating the options menu by //receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods. } @Override public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){ //Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. // For this method to be called, you must have first called setHasOptionsMenu(boolean). inflater.inflate(R.menu.forecastfragment, menu); // MenuInflater: This class is used to instantiate menu XML files into Menu objects. //public void inflate (int menuRes, Menu menu) : Inflate a menu hierarchy from the specified XML resource. } @Override public boolean onOptionsItemSelected(MenuItem item) { //notifies us when menu item selected // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //public abstract long getItemId (int position) : Get the row id associated with the specified position in the list. // Parameters : position , The position of the item within the adapter's data set whose row id we want. //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { //if Refresh button is clicked . FetchWeatherTask weatherTask = new FetchWeatherTask(); //initiate FetchWeatherTask weatherTask.execute("94043"); // return true; //for now we just return true. } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Called to have the fragment instantiate its user interface view. This is optional, // Returns the View for the fragment's UI, or null. String[] data = { // Create some dummy data for the ListView. Here's a sample weekly forecast "Mon 6/23 - Sunny - 31/17", "Tue 6/24 - Foggy - 21/8", "Wed 6/25 - Cloudy - 22/17", "Thurs 6/26 - Rainy - 18/11", "Fri 6/27 - Foggy - 21/10", "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18", "Sun 6/29 - Sunny - 20/7" }; List<String> weekForecast = new ArrayList<String>(Arrays.asList(data)); // Now that we have some dummy forecast data, create an ArrayAdapter. // The ArrayAdapter will take data from a source (like our dummy forecast) and // use it to populate the ListView it's attached to. mForecastAdapter = new ArrayAdapter<String>( // Constructor : // ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) getActivity(), // The current context (this activity) R.layout.list_item_forecast, // The name of the layout ID. R.id.list_item_forecast_textview, // The ID of the textview to populate. weekForecast); final View rootView = inflater.inflate(R.layout.fragment_main, container, false); //public View inflate (int resource, ViewGroup root, boolean attachToRoot): // Get a reference to the ListView, and attach this adapter to it. we cast it from R and indicate it's a ListView by CASTING. ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick (AdapterView<?> adapterView, View view, int position, long l){ String text = mForecastAdapter.getItem(position); int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(getActivity(), text, duration); toast.show(); //Complete version : Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show(); } }); return rootView; } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { //Returns String[] now as output. //AsyncTask : enables proper and easy use of the UI thread. This class allows to perform background //operations and publish results on the UI thread without having to manipulate threads and/or handlers. //AsyncTasks should ideally be used for short operations (a few seconds at the most.) // If you need to keep threads running for long periods of time,it is highly recommended you use the various APIs // provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask. private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); private String getReadableDateString(long time){ // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " + s); } return resultStrs; } @Override protected String[] doInBackground(String... params) { //String param "94043" is passed here. It will return String too. // These two need to be declared outside the try/catch // so that they can be closed in the finally block. if (params.length == 0){ return null; //if there's nothing to return. } HttpURLConnection urlConnection = null; //An URLConnection for HTTP (RFC 2616) used to send // and receive data over the web. Data may be of any type and length. // This class may be used to send and receive streaming data whose length is not known in advance. BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 7; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) //WE READ THE PASSED PARAM HERE. .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "Built URI " + builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); Log.v(LOG_TAG,"Forecast JSON String :" + forecastJsonStr); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, numDays); //Returning this String. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } protected void onPostExecute (String[] result){ if(result!=null){ mForecastAdapter.clear(); //result 0 a esit degilse , mock datayi siliyoruz. for (String dayForecastStr : result){ //yerine dayForecastStr'yi koyuyoruz . mForecastAdapter.add(dayForecastStr); //ve Adaptore ekliyoruz. } } } } }
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Encapsulates fetching the forecast and displaying it as a {@link ListView} layout. */ public class ForecastFragment extends Fragment { private ArrayAdapter<String> mForecastAdapter; //initializing the ArrayAdapter holds Strings public ForecastFragment() { //no-arg constructor , no needed actually but just in case if we want to automate it. } @Override public void onCreate(Bundle savedInstanceState){ //Called when the activity is starting //If the activity is being re-initialized after previously being shut down then this Bundle //contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null. super.onCreate(savedInstanceState); //Derived classes must call through to the super class's implementation of this method //Added this line in order for this fragment to handle menu events. setHasOptionsMenu(true); //Report that this fragment would like to participate in populating the options menu by //receiving a call to onCreateOptionsMenu(Menu, MenuInflater) and related methods. } @Override public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){ //Initialize the contents of the Activity's standard options menu. You should place your menu items in to menu. // For this method to be called, you must have first called setHasOptionsMenu(boolean). inflater.inflate(R.menu.forecastfragment, menu); // MenuInflater: This class is used to instantiate menu XML files into Menu objects. //public void inflate (int menuRes, Menu menu) : Inflate a menu hierarchy from the specified XML resource. } @Override public boolean onOptionsItemSelected(MenuItem item) { //notifies us when menu item selected // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //public abstract long getItemId (int position) : Get the row id associated with the specified position in the list. // Parameters : position , The position of the item within the adapter's data set whose row id we want. //noinspection SimplifiableIfStatement if (id == R.id.action_refresh) { //if Refresh button is clicked . FetchWeatherTask weatherTask = new FetchWeatherTask(); //initiate FetchWeatherTask weatherTask.execute("94043"); // return true; //for now we just return true. } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Called to have the fragment instantiate its user interface view. This is optional, // Returns the View for the fragment's UI, or null. String[] data = { // Create some dummy data for the ListView. Here's a sample weekly forecast "Mon 6/23 - Sunny - 31/17", "Tue 6/24 - Foggy - 21/8", "Wed 6/25 - Cloudy - 22/17", "Thurs 6/26 - Rainy - 18/11", "Fri 6/27 - Foggy - 21/10", "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18", "Sun 6/29 - Sunny - 20/7" }; List<String> weekForecast = new ArrayList<String>(Arrays.asList(data)); // Now that we have some dummy forecast data, create an ArrayAdapter. // The ArrayAdapter will take data from a source (like our dummy forecast) and // use it to populate the ListView it's attached to. mForecastAdapter = new ArrayAdapter<String>( // Constructor : // ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) getActivity(), // The current context (this activity) R.layout.list_item_forecast, // The name of the layout ID. R.id.list_item_forecast_textview, // The ID of the textview to populate. weekForecast); View rootView = inflater.inflate(R.layout.fragment_main, container, false); //public View inflate (int resource, ViewGroup root, boolean attachToRoot): // Get a reference to the ListView, and attach this adapter to it. we cast it from R and indicate it's a ListView by CASTING. ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); return rootView; } public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { //Returns String[] now as output. //AsyncTask : enables proper and easy use of the UI thread. This class allows to perform background //operations and publish results on the UI thread without having to manipulate threads and/or handlers. //AsyncTasks should ideally be used for short operations (a few seconds at the most.) // If you need to keep threads running for long periods of time,it is highly recommended you use the various APIs // provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask. private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); private String getReadableDateString(long time){ // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd"); return shortenedDateFormat.format(time); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". long dateTime; // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay+i); day = getReadableDateString(dateTime); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } for (String s : resultStrs) { Log.v(LOG_TAG, "Forecast entry: " + s); } return resultStrs; } @Override protected String[] doInBackground(String... params) { //String param "94043" is passed here. It will return String too. // These two need to be declared outside the try/catch // so that they can be closed in the finally block. if (params.length == 0){ return null; //if there's nothing to return. } HttpURLConnection urlConnection = null; //An URLConnection for HTTP (RFC 2616) used to send // and receive data over the web. Data may be of any type and length. // This class may be used to send and receive streaming data whose length is not known in advance. BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 7; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) //WE READ THE PASSED PARAM HERE. .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(builtUri.toString()); Log.v(LOG_TAG, "Built URI " + builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); Log.v(LOG_TAG,"Forecast JSON String :" + forecastJsonStr); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, numDays); //Returning this String. } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } protected void onPostExecute (String[] result){ if(result!=null){ mForecastAdapter.clear(); //result 0 a esit degilse , mock datayi siliyoruz. for (String dayForecastStr : result){ //yerine dayForecastStr'yi koyuyoruz . mForecastAdapter.add(dayForecastStr); //ve Adaptore ekliyoruz. } } } } }
3.01 Adding Toast and OnItemClicks onItemClickListener , onItemClick and Toast
app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java
3.01 Adding Toast and OnItemClicks onItemClickListener , onItemClick and Toast
<ide><path>pp/src/main/java/com/example/android/sunshine/app/ForecastFragment.java <ide> import android.view.MenuItem; <ide> import android.view.View; <ide> import android.view.ViewGroup; <add>import android.widget.AdapterView; <ide> import android.widget.ArrayAdapter; <ide> import android.widget.ListView; <add>import android.widget.Toast; <ide> <ide> import org.json.JSONArray; <ide> import org.json.JSONException; <ide> R.id.list_item_forecast_textview, // The ID of the textview to populate. <ide> weekForecast); <ide> <del> View rootView = inflater.inflate(R.layout.fragment_main, container, false); <add> final View rootView = inflater.inflate(R.layout.fragment_main, container, false); <ide> //public View inflate (int resource, ViewGroup root, boolean attachToRoot): <ide> <ide> // Get a reference to the ListView, and attach this adapter to it. we cast it from R and indicate it's a ListView by CASTING. <ide> ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); <ide> listView.setAdapter(mForecastAdapter); <del> <add> listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ <add> @Override <add> public void onItemClick (AdapterView<?> adapterView, View view, int position, long l){ <add> String text = mForecastAdapter.getItem(position); <add> int duration = Toast.LENGTH_SHORT; <add> <add> Toast toast = Toast.makeText(getActivity(), text, duration); <add> toast.show(); <add> //Complete version : Toast.makeText(getActivity(),text,Toast.LENGTH_SHORT).show(); <add> <add> } <add> }); <ide> return rootView; <ide> } <ide>
JavaScript
mit
7a2e7751726370fdc673f6d692972425b56ce06d
0
pimschaaf/dpi-grunt
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { dist: { src: [ 'js/functions.js', 'js/ready.js' ], dest: '../assets/js/main.concat.js' } }, jshint: { // define the files to lint files: ['js/**/*.js'], options: { // ignores: [''], globals: { jQuery: true, console: true, module: true } } }, watch: { //watch task js: { files: ['<%= jshint.files %>'], tasks: ['jshint', 'concat'] }, livereload: { // We use this target to watch files that will trigger the livereload files: [ // Anytime css is edited or compiled by sass, trigger the livereload on those files '../assets/css/*.css', // Or a js file '../assets/js/*.js' ], options: { livereload: true } } } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('build', ['jshint', 'concat']); //alias };
concat/gruntfile.js
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { dist: { src: [ 'js/functions.js', 'js/ready.js' ], dest: '../assets/js/main.concat.js' } }, jshint: { // define the files to lint files: ['js/**/*.js'], options: { // ignores: [''], globals: { jQuery: true, console: true, module: true } } }, watch: { //watch task js: { files: ['../assets/js/main.concat.js'], tasks: ['jshint', 'concat'] }, } }); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('build', ['jshint', 'concat']); //alias };
Update gruntfile.js
concat/gruntfile.js
Update gruntfile.js
<ide><path>oncat/gruntfile.js <ide> }, <ide> watch: { //watch task <ide> js: { <del> files: ['../assets/js/main.concat.js'], <add> files: ['<%= jshint.files %>'], <ide> tasks: ['jshint', 'concat'] <ide> }, <add> livereload: { <add> // We use this target to watch files that will trigger the livereload <add> files: [ <add> // Anytime css is edited or compiled by sass, trigger the livereload on those files <add> '../assets/css/*.css', <add> // Or a js file <add> '../assets/js/*.js' <add> ], <add> options: { livereload: true } <add> } <ide> } <ide> }); <ide>
Java
apache-2.0
7e04c2f6121438dd9966c327785b90c24b41cdff
0
gianpaj/mongo-java-driver,jyemin/mongo-java-driver,rozza/mongo-java-driver,kay-kim/mongo-java-driver,jyemin/mongo-java-driver,jsonking/mongo-java-driver,rozza/mongo-java-driver,jsonking/mongo-java-driver,PSCGroup/mongo-java-driver
/* * Copyright (c) 2008 - 2014 MongoDB Inc. <http://mongodb.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.mongodb; import org.bson.BSONBinarySubType; import org.bson.BSONBinaryWriter; import org.bson.BSONObject; import org.bson.BSONWriter; import org.bson.io.OutputBuffer; import org.bson.types.BSONTimestamp; import org.bson.types.Binary; import org.bson.types.Code; import org.bson.types.CodeWScope; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import org.junit.Test; import org.mongodb.Document; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static com.mongodb.DBObjectMatchers.hasSubdocument; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.mongodb.Fixture.disableMaxTimeFailPoint; import static org.mongodb.Fixture.enableMaxTimeFailPoint; import static org.mongodb.Fixture.isDiscoverableReplicaSet; import static org.mongodb.Fixture.isSharded; import static org.mongodb.Fixture.serverVersionAtLeast; public class DBCollectionTest extends DatabaseTestCase { @Test public void testDefaultSettings() { assertNull(collection.getDBDecoderFactory()); assertNull(collection.getDBEncoderFactory()); assertEquals(BasicDBObject.class, collection.getObjectClass()); assertNull(collection.getHintFields()); assertEquals(ReadPreference.primary(), collection.getReadPreference()); assertEquals(WriteConcern.ACKNOWLEDGED, collection.getWriteConcern()); assertEquals(0, collection.getOptions()); } @Test public void testInsert() { WriteResult res = collection.insert(new BasicDBObject("_id", 1).append("x", 2)); assertNotNull(res); assertEquals(1L, collection.count()); assertEquals(new BasicDBObject("_id", 1).append("x", 2), collection.findOne()); } @Test public void testInsertDuplicateKeyException() { DBObject doc = new BasicDBObject("_id", 1); collection.insert(doc, WriteConcern.ACKNOWLEDGED); try { collection.insert(doc, WriteConcern.ACKNOWLEDGED); fail("should throw DuplicateKey exception"); } catch (MongoDuplicateKeyException e) { assertThat(e.getCode(), is(11000)); } } @Test public void testSaveDuplicateKeyException() { collection.createIndex(new BasicDBObject("x", 1), new BasicDBObject("unique", true)); collection.save(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED); try { collection.save(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED); fail("should throw DuplicateKey exception"); } catch (MongoDuplicateKeyException e) { assertThat(e.getCode(), is(11000)); } } @Test public void testSaveWithIdDefined() { DBObject document = new BasicDBObject("_id", new ObjectId()).append("a", Math.random()); collection.save(document); assertThat(collection.count(), is(1L)); assertEquals(document, collection.findOne()); } @Test public void testUpdate() { WriteResult res = collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$set", new BasicDBObject("x", 2)), true, false); assertNotNull(res); assertEquals(1L, collection.count()); assertEquals(new BasicDBObject("_id", 1).append("x", 2), collection.findOne()); } @Test public void testObjectClass() { collection.setObjectClass(MyDBObject.class); collection.insert(new BasicDBObject("_id", 1)); DBObject obj = collection.findOne(); assertEquals(MyDBObject.class, obj.getClass()); } @Test public void testDotInDBObject() { try { collection.save(new BasicDBObject("x.y", 1)); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } try { collection.save(new BasicDBObject("x", new BasicDBObject("a.b", 1))); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } try { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("a.b", 1); collection.save(new BasicDBObject("x", map)); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } } @Test(expected = IllegalArgumentException.class) public void testJAVA794() { Map<String, String> nested = new HashMap<String, String>(); nested.put("my.dot.field", "foo"); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); list.add(nested); collection.save(new BasicDBObject("_document_", new BasicDBObject("array", list))); } @Test public void testInsertWithDBEncoder() { List<DBObject> objects = new ArrayList<DBObject>(); objects.add(new BasicDBObject("a", 1)); collection.insert(objects, WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(MyEncoder.getConstantObject(), collection.findOne()); } @Test public void testInsertWithDBEncoderFactorySet() { collection.setDBEncoderFactory(new MyEncoderFactory()); List<DBObject> objects = new ArrayList<DBObject>(); objects.add(new BasicDBObject("a", 1)); collection.insert(objects, WriteConcern.ACKNOWLEDGED, null); assertEquals(MyEncoder.getConstantObject(), collection.findOne()); collection.setDBEncoderFactory(null); } @Test(expected = UnsupportedOperationException.class) public void testCreateIndexWithInvalidIndexType() { DBObject index = new BasicDBObject("x", "funny"); collection.createIndex(index); } @Test public void testCreateIndexAsAscending() { DBObject index = new BasicDBObject("x", 1); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAsDescending() { DBObject index = new BasicDBObject("x", -1); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAs2d() { DBObject index = new BasicDBObject("x", "2d"); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAsText() { assumeTrue(serverVersionAtLeast(asList(2, 5, 5))); DBObject index = new BasicDBObject("x", "text"); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testRemoveWithDBEncoder() { DBObject document = new BasicDBObject("x", 1); collection.insert(document); collection.insert(MyEncoder.getConstantObject()); collection.remove(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(1, collection.count()); assertEquals(document, collection.findOne()); } @Test public void testCount() { for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("_id", i)); } assertEquals(10, collection.getCount()); assertEquals(5, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)))); assertEquals(4, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)), null, 100, 1)); assertEquals(4, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)), null, 4, 0)); } @Test public void testUpdateWithDBEncoder() { DBObject document = new BasicDBObject("x", 1); collection.insert(document); collection.update(new BasicDBObject("x", 1), new BasicDBObject("y", false), true, false, WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(2, collection.count()); assertThat(collection.find(), hasItem(MyEncoder.getConstantObject())); } @Test public void testFindAndRemove() { DBObject doc = new BasicDBObject("_id", 1).append("x", true); collection.insert(doc); DBObject newDoc = collection.findAndRemove(new BasicDBObject("_id", 1)); assertEquals(doc, newDoc); assertEquals(0, collection.count()); } @Test public void testFindAndReplace() { DBObject doc1 = new BasicDBObject("_id", 1).append("x", true); DBObject doc2 = new BasicDBObject("_id", 1).append("y", false); collection.insert(doc1); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", true), doc2); assertEquals(doc1, newDoc); assertEquals(doc2, collection.findOne()); } @Test public void testFindAndReplaceOrInsert() { collection.insert(new BasicDBObject("_id", 1).append("p", "abc")); DBObject doc = new BasicDBObject("_id", 2).append("p", "foo"); DBObject newDoc = collection.findAndModify(new BasicDBObject("p", "bar"), null, null, false, doc, false, true); assertNull(newDoc); assertEquals(doc, collection.findOne(null, null, new BasicDBObject("_id", -1))); } @Test public void testFindAndUpdate() { collection.insert(new BasicDBObject("_id", 1).append("x", true)); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", true), new BasicDBObject("$set", new BasicDBObject("x", false))); assertNotNull(newDoc); assertEquals(new BasicDBObject("_id", 1).append("x", true), newDoc); assertEquals(new BasicDBObject("_id", 1).append("x", false), collection.findOne()); } @Test public void findAndUpdateAndReturnNew() { collection.insert(new BasicDBObject("_id", 1).append("x", true)); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", false), null, null, false, new BasicDBObject("$set", new BasicDBObject("x", false)), true, true); assertNotNull(newDoc); assertThat(newDoc, hasSubdocument(new BasicDBObject("x", false))); } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndUpdateTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$set", new BasicDBObject("x", 1)), false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndReplaceTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("x", 1), false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndRemoveTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, true, null, false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test public void testGenericBinary() { byte[] data = {1, 2, 3}; collection.insert(new BasicDBObject("binary", new Binary(data))); assertArrayEquals(data, (byte[]) collection.findOne().get("binary")); } @Test public void testOtherBinary() { byte[] data = {1, 2, 3}; Binary binaryValue = new Binary(BSONBinarySubType.USER_DEFINED, data); collection.insert(new BasicDBObject("binary", binaryValue)); assertEquals(binaryValue, collection.findOne().get("binary")); } @Test public void testUUID() { UUID uuid = UUID.randomUUID(); collection.insert(new BasicDBObject("uuid", uuid)); assertEquals(uuid, collection.findOne().get("uuid")); } @Test(expected = IllegalArgumentException.class) public void testDotKeysArrayFail() { //JAVA-794 DBObject obj = new BasicDBObject("x", 1).append("y", 2) .append("array", new Object[]{new BasicDBObject("foo.bar", "baz")}); collection.insert(obj); } @Test(expected = IllegalArgumentException.class) public void testDotKeysListFail() { //JAVA-794 DBObject obj = new BasicDBObject("x", 1).append("y", 2) .append("array", asList(new BasicDBObject("foo.bar", "baz"))); collection.insert(obj); } @Test public void testPathToClassMapDecoding() { collection.setObjectClass(TopLevelDBObject.class); collection.setInternalClass("a", NestedOneDBObject.class); collection.setInternalClass("a.b", NestedTwoDBObject.class); DBObject doc = new TopLevelDBObject().append("a", new NestedOneDBObject().append("b", asList(new NestedTwoDBObject())) .append("c", new BasicDBObject())); collection.save(doc); assertEquals(doc, collection.findOne()); } @Test public void testReflectionObject() { collection.setObjectClass(Tweet.class); collection.insert(new Tweet(1, "Lorem", new Date(12))); assertThat(collection.count(), is(1L)); DBObject document = collection.findOne(); assertThat(document, instanceOf(Tweet.class)); Tweet tweet = (Tweet) document; assertThat(tweet.getUserId(), is(1L)); assertThat(tweet.getMessage(), is("Lorem")); assertThat(tweet.getDate(), is(new Date(12))); } @Test public void testReflectionObjectAtLeve2() { collection.insert(new BasicDBObject("t", new Tweet(1, "Lorem", new Date(12)))); collection.setInternalClass("t", Tweet.class); DBObject document = collection.findOne(); assertThat(document.get("t"), instanceOf(Tweet.class)); Tweet tweet = (Tweet) document.get("t"); assertThat(tweet.getUserId(), is(1L)); assertThat(tweet.getMessage(), is("Lorem")); assertThat(tweet.getDate(), is(new Date(12))); } @Test public void shouldAcceptDocumentsWithAllValidValueTypes() { BasicDBObject doc = new BasicDBObject(); doc.append("_id", new ObjectId()); doc.append("bool", true); doc.append("int", 3); doc.append("short", (short) 4); doc.append("long", 5L); doc.append("str", "Hello MongoDB"); doc.append("float", 6.0f); doc.append("double", 1.1); doc.append("date", new Date()); doc.append("ts", new BSONTimestamp(5, 1)); doc.append("pattern", Pattern.compile(".*")); doc.append("minKey", new MinKey()); doc.append("maxKey", new MaxKey()); doc.append("js", new Code("code")); doc.append("jsWithScope", new CodeWScope("code", new BasicDBObject())); doc.append("null", null); doc.append("uuid", UUID.randomUUID()); doc.append("db ref", new com.mongodb.DBRef(collection.getDB(), "test", new ObjectId())); doc.append("binary", new Binary((byte) 42, new byte[]{10, 11, 12})); doc.append("byte array", new byte[]{1, 2, 3}); doc.append("int array", new int[]{4, 5, 6}); doc.append("list", asList(7, 8, 9)); doc.append("doc list", asList(new Document("x", 1), new Document("x", 2))); collection.insert(doc); DBObject found = collection.findOne(); assertNotNull(found); assertEquals(ObjectId.class, found.get("_id").getClass()); assertEquals(Boolean.class, found.get("bool").getClass()); assertEquals(Integer.class, found.get("int").getClass()); assertEquals(Integer.class, found.get("short").getClass()); assertEquals(Long.class, found.get("long").getClass()); assertEquals(String.class, found.get("str").getClass()); assertEquals(Double.class, found.get("float").getClass()); assertEquals(Double.class, found.get("double").getClass()); assertEquals(Date.class, found.get("date").getClass()); assertEquals(BSONTimestamp.class, found.get("ts").getClass()); assertEquals(Pattern.class, found.get("pattern").getClass()); assertEquals(MinKey.class, found.get("minKey").getClass()); assertEquals(MaxKey.class, found.get("maxKey").getClass()); assertEquals(Code.class, found.get("js").getClass()); assertEquals(CodeWScope.class, found.get("jsWithScope").getClass()); assertNull(found.get("null")); assertEquals(UUID.class, found.get("uuid").getClass()); assertEquals(DBRef.class, found.get("db ref").getClass()); assertEquals(Binary.class, found.get("binary").getClass()); assertEquals(byte[].class, found.get("byte array").getClass()); assertTrue(found.get("int array") instanceof List); assertTrue(found.get("list") instanceof List); assertTrue(found.get("doc list") instanceof List); } @Test public void testCompoundCodecWithDefaultValues() { assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getDecoder(), instanceOf(CollectibleDBObjectCodec.class)); assertThat(codec.getEncoder(), instanceOf(CollectibleDBObjectCodec.class)); } @Test public void testCompoundCodecWithCustomEncoderFactory() { collection.setDBEncoderFactory(new DBEncoderFactory() { @Override public DBEncoder create() { return new DefaultDBEncoder(); } }); assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getEncoder(), instanceOf(DBEncoderFactoryAdapter.class)); } @Test public void testCompoundCodecWithCustomDecoderFactory() { collection.setDBDecoderFactory(new DBDecoderFactory() { @Override public DBDecoder create() { return new DefaultDBDecoder(); } }); assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getDecoder(), instanceOf(DBDecoderAdapter.class)); } @Test public void testBulkWriteOperation() { // given collection.insert(Arrays.<DBObject>asList(new BasicDBObject("_id", 3), new BasicDBObject("_id", 4), new BasicDBObject("_id", 5), new BasicDBObject("_id", 6).append("z", 1), new BasicDBObject("_id", 7).append("z", 1), new BasicDBObject("_id", 8).append("z", 2), new BasicDBObject("_id", 9).append("z", 2))); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); ObjectId upsertOneId = new ObjectId(); ObjectId upsertTwoId = new ObjectId(); bulkWriteOperation.find(new BasicDBObject("_id", upsertOneId)).upsert() .updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2))); bulkWriteOperation.find(new BasicDBObject("_id", upsertTwoId)).upsert() .replaceOne(new BasicDBObject("_id", upsertTwoId).append("y", 2)); bulkWriteOperation.find(new BasicDBObject("_id", 3)).removeOne(); bulkWriteOperation.find(new BasicDBObject("_id", 4)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 1))); bulkWriteOperation.find(new BasicDBObject("_id", 5)).replaceOne(new BasicDBObject("_id", 5).append("y", 1)); bulkWriteOperation.find(new BasicDBObject("z", 1)).remove(); bulkWriteOperation.find(new BasicDBObject("z", 2)).update(new BasicDBObject("$set", new BasicDBObject("z", 3))); BulkWriteResult result = bulkWriteOperation.execute(); // then assertTrue(bulkWriteOperation.isOrdered()); assertTrue(result.isAcknowledged()); assertEquals(1, result.getInsertedCount()); assertEquals(4, result.getUpdatedCount()); assertEquals(3, result.getRemovedCount()); assertEquals(4, result.getModifiedCount()); assertEquals(Arrays.asList(new BulkWriteUpsert(1, upsertOneId), new BulkWriteUpsert(2, upsertTwoId)), result.getUpserts()); assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 4).append("x", 1), new BasicDBObject("_id", 5).append("y", 1), new BasicDBObject("_id", 8).append("z", 3), new BasicDBObject("_id", 9).append("z", 3), new BasicDBObject("_id", upsertOneId).append("x", 2), new BasicDBObject("_id", upsertTwoId).append("y", 2)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test public void testOrderedBulkWriteOperation() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.insert(new BasicDBObject("_id", 2)); try { bulkWriteOperation.execute(); fail(); } catch (BulkWriteException e) { assertEquals(1, e.getWriteErrors().size()); } assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 1)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test public void testUnorderedBulkWriteOperation() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeUnorderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.insert(new BasicDBObject("_id", 2)); try { bulkWriteOperation.execute(); fail(); } catch (BulkWriteException e) { assertEquals(1, e.getWriteErrors().size()); } assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test(expected = BulkWriteException.class) public void testBulkWriteException() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.execute(); } @Test public void testWriteConcernExceptionOnInsert() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); WriteResult res = localCollection.insert(new BasicDBObject(), new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(0, e.getCommandResult().get("n")); } finally { mongoClient.close(); } } @Test public void testWriteConcernExceptionOnUpdate() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); ObjectId id = new ObjectId(); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); WriteResult res = localCollection.update(new BasicDBObject("_id", id), new BasicDBObject("$set", new BasicDBObject("x", 1)), true, false, new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(1, e.getCommandResult().get("n")); assertEquals(id, e.getCommandResult().get("upserted")); } finally { mongoClient.close(); } } @Test public void testWriteConcernExceptionOnRemove() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); localCollection.insert(new BasicDBObject()); WriteResult res = localCollection.remove(new BasicDBObject(), new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(1, e.getCommandResult().get("n")); } finally { mongoClient.close(); } } @Test public void testBulkWriteConcernException() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); BulkWriteOperation bulkWriteOperation = localCollection.initializeUnorderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject()); BulkWriteResult res = bulkWriteOperation.execute(new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (BulkWriteException e) { assertNotNull(e.getWriteConcernError()); // unclear what else we can reliably assert here } finally { mongoClient.close(); } } public static class MyDBObject extends BasicDBObject { private static final long serialVersionUID = 3352369936048544621L; } // used via reflection @SuppressWarnings("UnusedDeclaration") public static class Tweet extends ReflectionDBObject { private long userId; private String message; private Date date; public Tweet(final long userId, final String message, final Date date) { this.userId = userId; this.message = message; this.date = date; } public Tweet() { } public long getUserId() { return userId; } public void setUserId(final long userId) { this.userId = userId; } public String getMessage() { return message; } public void setMessage(final String message) { this.message = message; } public Date getDate() { return date; } public void setDate(final Date date) { this.date = date; } } public static class MyEncoder implements DBEncoder { @Override public int writeObject(final OutputBuffer outputBuffer, final BSONObject document) { int start = outputBuffer.getPosition(); BSONWriter bsonWriter = new BSONBinaryWriter(outputBuffer, false); try { bsonWriter.writeStartDocument(); bsonWriter.writeInt32("_id", 1); bsonWriter.writeString("s", "foo"); bsonWriter.writeEndDocument(); return outputBuffer.getPosition() - start; } finally { bsonWriter.close(); } } public static DBObject getConstantObject() { return new BasicDBObject() .append("_id", 1) .append("s", "foo"); } } public static class MyEncoderFactory implements DBEncoderFactory { @Override public DBEncoder create() { return new MyEncoder(); } } public static class MyIndexDBEncoder implements DBEncoder { private final String ns; public MyIndexDBEncoder(final String ns) { this.ns = ns; } @Override public int writeObject(final OutputBuffer outputBuffer, final BSONObject document) { int start = outputBuffer.getPosition(); BSONWriter bsonWriter = new BSONBinaryWriter(outputBuffer, false); try { bsonWriter.writeStartDocument(); bsonWriter.writeString("name", "z_1"); bsonWriter.writeStartDocument("key"); bsonWriter.writeInt32("z", 1); bsonWriter.writeEndDocument(); bsonWriter.writeBoolean("unique", true); bsonWriter.writeString("ns", ns); bsonWriter.writeEndDocument(); return outputBuffer.getPosition() - start; } finally { bsonWriter.close(); } } } public static class TopLevelDBObject extends BasicDBObject { private static final long serialVersionUID = 7029929727222305692L; } public static class NestedOneDBObject extends BasicDBObject { private static final long serialVersionUID = -5821458746671670383L; } public static class NestedTwoDBObject extends BasicDBObject { private static final long serialVersionUID = 5243874721805359328L; } }
driver-compat/src/test/unit/com/mongodb/DBCollectionTest.java
/* * Copyright (c) 2008 - 2014 MongoDB Inc. <http://mongodb.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.mongodb; import org.bson.BSONBinarySubType; import org.bson.BSONBinaryWriter; import org.bson.BSONObject; import org.bson.BSONWriter; import org.bson.io.OutputBuffer; import org.bson.types.BSONTimestamp; import org.bson.types.Binary; import org.bson.types.Code; import org.bson.types.CodeWScope; import org.bson.types.MaxKey; import org.bson.types.MinKey; import org.bson.types.ObjectId; import org.junit.Ignore; import org.junit.Test; import org.mongodb.Document; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static com.mongodb.DBObjectMatchers.hasSubdocument; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import static org.mongodb.Fixture.disableMaxTimeFailPoint; import static org.mongodb.Fixture.enableMaxTimeFailPoint; import static org.mongodb.Fixture.isDiscoverableReplicaSet; import static org.mongodb.Fixture.isSharded; import static org.mongodb.Fixture.serverVersionAtLeast; public class DBCollectionTest extends DatabaseTestCase { @Test public void testDefaultSettings() { assertNull(collection.getDBDecoderFactory()); assertNull(collection.getDBEncoderFactory()); assertEquals(BasicDBObject.class, collection.getObjectClass()); assertNull(collection.getHintFields()); assertEquals(ReadPreference.primary(), collection.getReadPreference()); assertEquals(WriteConcern.ACKNOWLEDGED, collection.getWriteConcern()); assertEquals(0, collection.getOptions()); } @Test public void testInsert() { WriteResult res = collection.insert(new BasicDBObject("_id", 1).append("x", 2)); assertNotNull(res); assertEquals(1L, collection.count()); assertEquals(new BasicDBObject("_id", 1).append("x", 2), collection.findOne()); } @Test public void testInsertDuplicateKeyException() { DBObject doc = new BasicDBObject("_id", 1); collection.insert(doc, WriteConcern.ACKNOWLEDGED); try { collection.insert(doc, WriteConcern.ACKNOWLEDGED); fail("should throw DuplicateKey exception"); } catch (MongoDuplicateKeyException e) { assertThat(e.getCode(), is(11000)); } } @Test public void testSaveDuplicateKeyException() { collection.createIndex(new BasicDBObject("x", 1), new BasicDBObject("unique", true)); collection.save(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED); try { collection.save(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED); fail("should throw DuplicateKey exception"); } catch (MongoDuplicateKeyException e) { assertThat(e.getCode(), is(11000)); } } @Test public void testSaveWithIdDefined() { DBObject document = new BasicDBObject("_id", new ObjectId()).append("a", Math.random()); collection.save(document); assertThat(collection.count(), is(1L)); assertEquals(document, collection.findOne()); } @Test public void testUpdate() { WriteResult res = collection.update(new BasicDBObject("_id", 1), new BasicDBObject("$set", new BasicDBObject("x", 2)), true, false); assertNotNull(res); assertEquals(1L, collection.count()); assertEquals(new BasicDBObject("_id", 1).append("x", 2), collection.findOne()); } @Test public void testObjectClass() { collection.setObjectClass(MyDBObject.class); collection.insert(new BasicDBObject("_id", 1)); DBObject obj = collection.findOne(); assertEquals(MyDBObject.class, obj.getClass()); } @Test public void testDotInDBObject() { try { collection.save(new BasicDBObject("x.y", 1)); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } try { collection.save(new BasicDBObject("x", new BasicDBObject("a.b", 1))); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } try { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("a.b", 1); collection.save(new BasicDBObject("x", map)); fail("Should throw exception"); } catch (IllegalArgumentException e) { // all good } } @Test(expected = IllegalArgumentException.class) public void testJAVA794() { Map<String, String> nested = new HashMap<String, String>(); nested.put("my.dot.field", "foo"); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); list.add(nested); collection.save(new BasicDBObject("_document_", new BasicDBObject("array", list))); } @Test public void testInsertWithDBEncoder() { List<DBObject> objects = new ArrayList<DBObject>(); objects.add(new BasicDBObject("a", 1)); collection.insert(objects, WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(MyEncoder.getConstantObject(), collection.findOne()); } @Test public void testInsertWithDBEncoderFactorySet() { collection.setDBEncoderFactory(new MyEncoderFactory()); List<DBObject> objects = new ArrayList<DBObject>(); objects.add(new BasicDBObject("a", 1)); collection.insert(objects, WriteConcern.ACKNOWLEDGED, null); assertEquals(MyEncoder.getConstantObject(), collection.findOne()); collection.setDBEncoderFactory(null); } @Test(expected = UnsupportedOperationException.class) public void testCreateIndexWithInvalidIndexType() { DBObject index = new BasicDBObject("x", "funny"); collection.createIndex(index); } @Test public void testCreateIndexAsAscending() { DBObject index = new BasicDBObject("x", 1); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAsDescending() { DBObject index = new BasicDBObject("x", -1); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAs2d() { DBObject index = new BasicDBObject("x", "2d"); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testCreateIndexAsText() { assumeTrue(serverVersionAtLeast(asList(2, 5, 5))); DBObject index = new BasicDBObject("x", "text"); collection.createIndex(index); assertThat(collection.getIndexInfo(), notNullValue()); } @Test public void testRemoveWithDBEncoder() { DBObject document = new BasicDBObject("x", 1); collection.insert(document); collection.insert(MyEncoder.getConstantObject()); collection.remove(new BasicDBObject("x", 1), WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(1, collection.count()); assertEquals(document, collection.findOne()); } @Test public void testCount() { for (int i = 0; i < 10; i++) { collection.insert(new BasicDBObject("_id", i)); } assertEquals(10, collection.getCount()); assertEquals(5, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)))); assertEquals(4, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)), null, 100, 1)); assertEquals(4, collection.getCount(new BasicDBObject("_id", new BasicDBObject("$lt", 5)), null, 4, 0)); } @Test public void testUpdateWithDBEncoder() { DBObject document = new BasicDBObject("x", 1); collection.insert(document); collection.update(new BasicDBObject("x", 1), new BasicDBObject("y", false), true, false, WriteConcern.ACKNOWLEDGED, new MyEncoder()); assertEquals(2, collection.count()); assertThat(collection.find(), hasItem(MyEncoder.getConstantObject())); } @Test public void testFindAndRemove() { DBObject doc = new BasicDBObject("_id", 1).append("x", true); collection.insert(doc); DBObject newDoc = collection.findAndRemove(new BasicDBObject("_id", 1)); assertEquals(doc, newDoc); assertEquals(0, collection.count()); } @Test public void testFindAndReplace() { DBObject doc1 = new BasicDBObject("_id", 1).append("x", true); DBObject doc2 = new BasicDBObject("_id", 1).append("y", false); collection.insert(doc1); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", true), doc2); assertEquals(doc1, newDoc); assertEquals(doc2, collection.findOne()); } @Test public void testFindAndReplaceOrInsert() { collection.insert(new BasicDBObject("_id", 1).append("p", "abc")); DBObject doc = new BasicDBObject("_id", 2).append("p", "foo"); DBObject newDoc = collection.findAndModify(new BasicDBObject("p", "bar"), null, null, false, doc, false, true); assertNull(newDoc); assertEquals(doc, collection.findOne(null, null, new BasicDBObject("_id", -1))); } @Test public void testFindAndUpdate() { collection.insert(new BasicDBObject("_id", 1).append("x", true)); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", true), new BasicDBObject("$set", new BasicDBObject("x", false))); assertNotNull(newDoc); assertEquals(new BasicDBObject("_id", 1).append("x", true), newDoc); assertEquals(new BasicDBObject("_id", 1).append("x", false), collection.findOne()); } @Test public void findAndUpdateAndReturnNew() { collection.insert(new BasicDBObject("_id", 1).append("x", true)); DBObject newDoc = collection.findAndModify(new BasicDBObject("x", false), null, null, false, new BasicDBObject("$set", new BasicDBObject("x", false)), true, true); assertNotNull(newDoc); assertThat(newDoc, hasSubdocument(new BasicDBObject("x", false))); } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndUpdateTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("$set", new BasicDBObject("x", 1)), false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndReplaceTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, false, new BasicDBObject("x", 1), false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test(expected = MongoExecutionTimeoutException.class) public void testFindAndRemoveTimeout() { assumeFalse(isSharded()); assumeTrue(serverVersionAtLeast(asList(2, 5, 3))); collection.insert(new BasicDBObject("_id", 1)); enableMaxTimeFailPoint(); try { collection.findAndModify(new BasicDBObject("_id", 1), null, null, true, null, false, false, 1, TimeUnit.SECONDS); } finally { disableMaxTimeFailPoint(); } } @Test public void testGenericBinary() { byte[] data = {1, 2, 3}; collection.insert(new BasicDBObject("binary", new Binary(data))); assertArrayEquals(data, (byte[]) collection.findOne().get("binary")); } @Test public void testOtherBinary() { byte[] data = {1, 2, 3}; Binary binaryValue = new Binary(BSONBinarySubType.USER_DEFINED, data); collection.insert(new BasicDBObject("binary", binaryValue)); assertEquals(binaryValue, collection.findOne().get("binary")); } @Test public void testUUID() { UUID uuid = UUID.randomUUID(); collection.insert(new BasicDBObject("uuid", uuid)); assertEquals(uuid, collection.findOne().get("uuid")); } @Test(expected = IllegalArgumentException.class) public void testDotKeysArrayFail() { //JAVA-794 DBObject obj = new BasicDBObject("x", 1).append("y", 2) .append("array", new Object[]{new BasicDBObject("foo.bar", "baz")}); collection.insert(obj); } @Test(expected = IllegalArgumentException.class) public void testDotKeysListFail() { //JAVA-794 DBObject obj = new BasicDBObject("x", 1).append("y", 2) .append("array", asList(new BasicDBObject("foo.bar", "baz"))); collection.insert(obj); } @Test public void testPathToClassMapDecoding() { collection.setObjectClass(TopLevelDBObject.class); collection.setInternalClass("a", NestedOneDBObject.class); collection.setInternalClass("a.b", NestedTwoDBObject.class); DBObject doc = new TopLevelDBObject().append("a", new NestedOneDBObject().append("b", asList(new NestedTwoDBObject())) .append("c", new BasicDBObject())); collection.save(doc); assertEquals(doc, collection.findOne()); } @Test public void testReflectionObject() { collection.setObjectClass(Tweet.class); collection.insert(new Tweet(1, "Lorem", new Date(12))); assertThat(collection.count(), is(1L)); DBObject document = collection.findOne(); assertThat(document, instanceOf(Tweet.class)); Tweet tweet = (Tweet) document; assertThat(tweet.getUserId(), is(1L)); assertThat(tweet.getMessage(), is("Lorem")); assertThat(tweet.getDate(), is(new Date(12))); } @Test public void testReflectionObjectAtLeve2() { collection.insert(new BasicDBObject("t", new Tweet(1, "Lorem", new Date(12)))); collection.setInternalClass("t", Tweet.class); DBObject document = collection.findOne(); assertThat(document.get("t"), instanceOf(Tweet.class)); Tweet tweet = (Tweet) document.get("t"); assertThat(tweet.getUserId(), is(1L)); assertThat(tweet.getMessage(), is("Lorem")); assertThat(tweet.getDate(), is(new Date(12))); } @Test public void shouldAcceptDocumentsWithAllValidValueTypes() { BasicDBObject doc = new BasicDBObject(); doc.append("_id", new ObjectId()); doc.append("bool", true); doc.append("int", 3); doc.append("short", (short) 4); doc.append("long", 5L); doc.append("str", "Hello MongoDB"); doc.append("float", 6.0f); doc.append("double", 1.1); doc.append("date", new Date()); doc.append("ts", new BSONTimestamp(5, 1)); doc.append("pattern", Pattern.compile(".*")); doc.append("minKey", new MinKey()); doc.append("maxKey", new MaxKey()); doc.append("js", new Code("code")); doc.append("jsWithScope", new CodeWScope("code", new BasicDBObject())); doc.append("null", null); doc.append("uuid", UUID.randomUUID()); doc.append("db ref", new com.mongodb.DBRef(collection.getDB(), "test", new ObjectId())); doc.append("binary", new Binary((byte) 42, new byte[]{10, 11, 12})); doc.append("byte array", new byte[]{1, 2, 3}); doc.append("int array", new int[]{4, 5, 6}); doc.append("list", asList(7, 8, 9)); doc.append("doc list", asList(new Document("x", 1), new Document("x", 2))); collection.insert(doc); DBObject found = collection.findOne(); assertNotNull(found); assertEquals(ObjectId.class, found.get("_id").getClass()); assertEquals(Boolean.class, found.get("bool").getClass()); assertEquals(Integer.class, found.get("int").getClass()); assertEquals(Integer.class, found.get("short").getClass()); assertEquals(Long.class, found.get("long").getClass()); assertEquals(String.class, found.get("str").getClass()); assertEquals(Double.class, found.get("float").getClass()); assertEquals(Double.class, found.get("double").getClass()); assertEquals(Date.class, found.get("date").getClass()); assertEquals(BSONTimestamp.class, found.get("ts").getClass()); assertEquals(Pattern.class, found.get("pattern").getClass()); assertEquals(MinKey.class, found.get("minKey").getClass()); assertEquals(MaxKey.class, found.get("maxKey").getClass()); assertEquals(Code.class, found.get("js").getClass()); assertEquals(CodeWScope.class, found.get("jsWithScope").getClass()); assertNull(found.get("null")); assertEquals(UUID.class, found.get("uuid").getClass()); assertEquals(DBRef.class, found.get("db ref").getClass()); assertEquals(Binary.class, found.get("binary").getClass()); assertEquals(byte[].class, found.get("byte array").getClass()); assertTrue(found.get("int array") instanceof List); assertTrue(found.get("list") instanceof List); assertTrue(found.get("doc list") instanceof List); } @Test public void testCompoundCodecWithDefaultValues() { assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getDecoder(), instanceOf(CollectibleDBObjectCodec.class)); assertThat(codec.getEncoder(), instanceOf(CollectibleDBObjectCodec.class)); } @Test public void testCompoundCodecWithCustomEncoderFactory() { collection.setDBEncoderFactory(new DBEncoderFactory() { @Override public DBEncoder create() { return new DefaultDBEncoder(); } }); assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getEncoder(), instanceOf(DBEncoderFactoryAdapter.class)); } @Test public void testCompoundCodecWithCustomDecoderFactory() { collection.setDBDecoderFactory(new DBDecoderFactory() { @Override public DBDecoder create() { return new DefaultDBDecoder(); } }); assertThat(collection.getObjectCodec(), instanceOf(CompoundDBObjectCodec.class)); CompoundDBObjectCodec codec = (CompoundDBObjectCodec) collection.getObjectCodec(); assertThat(codec.getDecoder(), instanceOf(DBDecoderAdapter.class)); } @Test public void testBulkWriteOperation() { // given collection.insert(Arrays.<DBObject>asList(new BasicDBObject("_id", 3), new BasicDBObject("_id", 4), new BasicDBObject("_id", 5), new BasicDBObject("_id", 6).append("z", 1), new BasicDBObject("_id", 7).append("z", 1), new BasicDBObject("_id", 8).append("z", 2), new BasicDBObject("_id", 9).append("z", 2))); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); ObjectId upsertOneId = new ObjectId(); ObjectId upsertTwoId = new ObjectId(); bulkWriteOperation.find(new BasicDBObject("_id", upsertOneId)).upsert() .updateOne(new BasicDBObject("$set", new BasicDBObject("x", 2))); bulkWriteOperation.find(new BasicDBObject("_id", upsertTwoId)).upsert() .replaceOne(new BasicDBObject("_id", upsertTwoId).append("y", 2)); bulkWriteOperation.find(new BasicDBObject("_id", 3)).removeOne(); bulkWriteOperation.find(new BasicDBObject("_id", 4)).updateOne(new BasicDBObject("$set", new BasicDBObject("x", 1))); bulkWriteOperation.find(new BasicDBObject("_id", 5)).replaceOne(new BasicDBObject("_id", 5).append("y", 1)); bulkWriteOperation.find(new BasicDBObject("z", 1)).remove(); bulkWriteOperation.find(new BasicDBObject("z", 2)).update(new BasicDBObject("$set", new BasicDBObject("z", 3))); BulkWriteResult result = bulkWriteOperation.execute(); // then assertTrue(bulkWriteOperation.isOrdered()); assertTrue(result.isAcknowledged()); assertEquals(1, result.getInsertedCount()); assertEquals(4, result.getUpdatedCount()); assertEquals(3, result.getRemovedCount()); assertEquals(4, result.getModifiedCount()); assertEquals(Arrays.asList(new BulkWriteUpsert(1, upsertOneId), new BulkWriteUpsert(2, upsertTwoId)), result.getUpserts()); assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 4).append("x", 1), new BasicDBObject("_id", 5).append("y", 1), new BasicDBObject("_id", 8).append("z", 3), new BasicDBObject("_id", 9).append("z", 3), new BasicDBObject("_id", upsertOneId).append("x", 2), new BasicDBObject("_id", upsertTwoId).append("y", 2)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test public void testOrderedBulkWriteOperation() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.insert(new BasicDBObject("_id", 2)); try { bulkWriteOperation.execute(); fail(); } catch (BulkWriteException e) { assertEquals(1, e.getWriteErrors().size()); } assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 1)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test public void testUnorderedBulkWriteOperation() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeUnorderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 0)); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.insert(new BasicDBObject("_id", 2)); try { bulkWriteOperation.execute(); fail(); } catch (BulkWriteException e) { assertEquals(1, e.getWriteErrors().size()); } assertEquals(Arrays.<DBObject>asList(new BasicDBObject("_id", 0), new BasicDBObject("_id", 1), new BasicDBObject("_id", 2)), collection.find().sort(new BasicDBObject("_id", 1)).toArray()); } @Test(expected = BulkWriteException.class) public void testBulkWriteException() { // given collection.insert(new BasicDBObject("_id", 1)); // when BulkWriteOperation bulkWriteOperation = collection.initializeOrderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject("_id", 1)); bulkWriteOperation.execute(); } @Test public void testWriteConcernExceptionOnInsert() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); WriteResult res = localCollection.insert(new BasicDBObject(), new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(0, e.getCommandResult().get("n")); } finally { mongoClient.close(); } } @Test public void testWriteConcernExceptionOnUpdate() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); ObjectId id = new ObjectId(); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); WriteResult res = localCollection.update(new BasicDBObject("_id", id), new BasicDBObject("$set", new BasicDBObject("x", 1)), true, false, new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(1, e.getCommandResult().get("n")); assertEquals(id, e.getCommandResult().get("upserted")); } finally { mongoClient.close(); } } @Test public void testWriteConcernExceptionOnRemove() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); localCollection.insert(new BasicDBObject()); WriteResult res = localCollection.remove(new BasicDBObject(), new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (WriteConcernException e) { assertNotNull(e.getCommandResult().get("err")); assertEquals(1, e.getCommandResult().get("n")); } finally { mongoClient.close(); } } @Test public void testBulkWriteConcernException() throws UnknownHostException { assumeTrue(isDiscoverableReplicaSet()); MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress())); try { DBCollection localCollection = mongoClient.getDB(collection.getDB().getName()).getCollection(collection.getName()); BulkWriteOperation bulkWriteOperation = localCollection.initializeUnorderedBulkOperation(); bulkWriteOperation.insert(new BasicDBObject()); BulkWriteResult res = bulkWriteOperation.execute(new WriteConcern(5, 1, false, false)); fail("Write should have failed but succeeded with result " + res); } catch (BulkWriteException e) { assertNotNull(e.getWriteConcernError()); // unclear what else we can reliably assert here } finally { mongoClient.close(); } } public static class MyDBObject extends BasicDBObject { private static final long serialVersionUID = 3352369936048544621L; } // used via reflection @SuppressWarnings("UnusedDeclaration") public static class Tweet extends ReflectionDBObject { private long userId; private String message; private Date date; public Tweet(final long userId, final String message, final Date date) { this.userId = userId; this.message = message; this.date = date; } public Tweet() { } public long getUserId() { return userId; } public void setUserId(final long userId) { this.userId = userId; } public String getMessage() { return message; } public void setMessage(final String message) { this.message = message; } public Date getDate() { return date; } public void setDate(final Date date) { this.date = date; } } public static class MyEncoder implements DBEncoder { @Override public int writeObject(final OutputBuffer outputBuffer, final BSONObject document) { int start = outputBuffer.getPosition(); BSONWriter bsonWriter = new BSONBinaryWriter(outputBuffer, false); try { bsonWriter.writeStartDocument(); bsonWriter.writeInt32("_id", 1); bsonWriter.writeString("s", "foo"); bsonWriter.writeEndDocument(); return outputBuffer.getPosition() - start; } finally { bsonWriter.close(); } } public static DBObject getConstantObject() { return new BasicDBObject() .append("_id", 1) .append("s", "foo"); } } public static class MyEncoderFactory implements DBEncoderFactory { @Override public DBEncoder create() { return new MyEncoder(); } } public static class MyIndexDBEncoder implements DBEncoder { private final String ns; public MyIndexDBEncoder(final String ns) { this.ns = ns; } @Override public int writeObject(final OutputBuffer outputBuffer, final BSONObject document) { int start = outputBuffer.getPosition(); BSONWriter bsonWriter = new BSONBinaryWriter(outputBuffer, false); try { bsonWriter.writeStartDocument(); bsonWriter.writeString("name", "z_1"); bsonWriter.writeStartDocument("key"); bsonWriter.writeInt32("z", 1); bsonWriter.writeEndDocument(); bsonWriter.writeBoolean("unique", true); bsonWriter.writeString("ns", ns); bsonWriter.writeEndDocument(); return outputBuffer.getPosition() - start; } finally { bsonWriter.close(); } } } public static class TopLevelDBObject extends BasicDBObject { private static final long serialVersionUID = 7029929727222305692L; } public static class NestedOneDBObject extends BasicDBObject { private static final long serialVersionUID = -5821458746671670383L; } public static class NestedTwoDBObject extends BasicDBObject { private static final long serialVersionUID = 5243874721805359328L; } }
remove unused import
driver-compat/src/test/unit/com/mongodb/DBCollectionTest.java
remove unused import
<ide><path>river-compat/src/test/unit/com/mongodb/DBCollectionTest.java <ide> import org.bson.types.MaxKey; <ide> import org.bson.types.MinKey; <ide> import org.bson.types.ObjectId; <del>import org.junit.Ignore; <ide> import org.junit.Test; <ide> import org.mongodb.Document; <ide>
Java
apache-2.0
error: pathspec 'chapter_009/src/main/java/ru/job4j/concurrent/ConsoleProgress.java' did not match any file(s) known to git
016f6c7fdd839192fa9793e3fcf44dddee730494
1
IvanBelyaev/ibelyaev,IvanBelyaev/ibelyaev,IvanBelyaev/ibelyaev
package ru.job4j.concurrent; /** * ConsoleProgress. * * @author Ivan Belyaev * @version 1.0 * @since 12.05.2020 */ public class ConsoleProgress implements Runnable { /** * Simulates a download. */ @Override public void run() { final String[] symbols = {"—", "\\", "|", "/"}; int index = 0; while (!Thread.currentThread().isInterrupted()) { if (index == symbols.length) { index = 0; } System.out.printf("\r Loading ... %s", symbols[index++]); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.printf("%n%s is interrupted%n", Thread.currentThread().getName()); return; } } } /** * Entry point. * @param args command line arguments. Not used. * @throws InterruptedException - exception. */ public static void main(String[] args) throws InterruptedException { Thread progress = new Thread(new ConsoleProgress()); progress.start(); Thread.sleep(10000); progress.interrupt(); } }
chapter_009/src/main/java/ru/job4j/concurrent/ConsoleProgress.java
3. Прерывание нити [#283642]
chapter_009/src/main/java/ru/job4j/concurrent/ConsoleProgress.java
3. Прерывание нити [#283642]
<ide><path>hapter_009/src/main/java/ru/job4j/concurrent/ConsoleProgress.java <add>package ru.job4j.concurrent; <add> <add>/** <add> * ConsoleProgress. <add> * <add> * @author Ivan Belyaev <add> * @version 1.0 <add> * @since 12.05.2020 <add> */ <add>public class ConsoleProgress implements Runnable { <add> /** <add> * Simulates a download. <add> */ <add> @Override <add> public void run() { <add> final String[] symbols = {"—", "\\", "|", "/"}; <add> int index = 0; <add> while (!Thread.currentThread().isInterrupted()) { <add> if (index == symbols.length) { <add> index = 0; <add> } <add> System.out.printf("\r Loading ... %s", symbols[index++]); <add> try { <add> Thread.sleep(500); <add> } catch (InterruptedException e) { <add> System.out.printf("%n%s is interrupted%n", Thread.currentThread().getName()); <add> return; <add> } <add> } <add> } <add> <add> /** <add> * Entry point. <add> * @param args command line arguments. Not used. <add> * @throws InterruptedException - exception. <add> */ <add> public static void main(String[] args) throws InterruptedException { <add> Thread progress = new Thread(new ConsoleProgress()); <add> progress.start(); <add> Thread.sleep(10000); <add> progress.interrupt(); <add> } <add>}
Java
mit
ef2aa76a86d4cdb0b7baf13267829005773874b8
0
peterjosling/scroball
package com.peterjosling.scroball; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.google.common.collect.ImmutableList; import java.util.List; public class MainActivity extends AppCompatActivity { private ScroballApplication application; /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link FragmentPagerAdapter} derivative, which will keep every loaded * fragment in memory. If this becomes too memory intensive, it may be best to switch to a {@link * android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; /** The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); application = (ScroballApplication) getApplication(); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings_item: Intent intent = new Intent(getBaseContext(), SettingsActivity.class); startActivityForResult(intent, 1); return true; case R.id.logout_item: logout(); return true; default: return super.onOptionsItemSelected(item); } } public void logout() { new AlertDialog.Builder(this) .setTitle(R.string.are_you_sure) .setMessage(R.string.logout_confirm) .setPositiveButton( android.R.string.yes, (dialog, whichButton) -> { SharedPreferences preferences = application.getSharedPreferences(); SharedPreferences.Editor editor = preferences.edit(); editor.remove(getString(R.string.saved_session_key)); editor.apply(); application.getScroballDB().clear(); application.getLastfmClient().clearSession(); Intent intent = new Intent(this, SplashScreen.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }) .setNegativeButton(android.R.string.no, null) .show(); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the * sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { List<Fragment> fragments = ImmutableList.of(new NowPlayingFragment(), new ScrobbleHistoryFragment()); public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Now Playing"; case 1: return "History"; } return null; } } }
app/src/main/java/com/peterjosling/scroball/MainActivity.java
package com.peterjosling.scroball; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.google.common.collect.ImmutableList; import java.util.List; public class MainActivity extends AppCompatActivity { private ScroballApplication application; /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ private SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ private ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); application = (ScroballApplication) getApplication(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings_item: Intent intent = new Intent(getBaseContext(), SettingsActivity.class); startActivityForResult(intent, 1); return true; case R.id.logout_item: logout(); return true; default: return super.onOptionsItemSelected(item); } } public void logout() { new AlertDialog.Builder(this) .setTitle(R.string.are_you_sure) .setMessage(R.string.logout_confirm) .setPositiveButton(android.R.string.yes, (dialog, whichButton) -> { SharedPreferences preferences = application.getSharedPreferences(); SharedPreferences.Editor editor = preferences.edit(); editor.remove(getString(R.string.saved_session_key)); editor.apply(); application.getScroballDB().clear(); application.getLastfmClient().clearSession(); Intent intent = new Intent(this, SplashScreen.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); }) .setNegativeButton(android.R.string.no, null).show(); } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to * one of the sections/tabs/pages. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { List<Fragment> fragments = ImmutableList.of( new NowPlayingFragment(), new ScrobbleHistoryFragment()); public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "Now Playing"; case 1: return "History"; } return null; } } }
Clean up MainActivity • Remove redundant casts • Reformat
app/src/main/java/com/peterjosling/scroball/MainActivity.java
Clean up MainActivity
<ide><path>pp/src/main/java/com/peterjosling/scroball/MainActivity.java <ide> private ScroballApplication application; <ide> <ide> /** <del> * The {@link android.support.v4.view.PagerAdapter} that will provide <del> * fragments for each of the sections. We use a <del> * {@link FragmentPagerAdapter} derivative, which will keep every <del> * loaded fragment in memory. If this becomes too memory intensive, it <del> * may be best to switch to a <del> * {@link android.support.v4.app.FragmentStatePagerAdapter}. <add> * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the <add> * sections. We use a {@link FragmentPagerAdapter} derivative, which will keep every loaded <add> * fragment in memory. If this becomes too memory intensive, it may be best to switch to a {@link <add> * android.support.v4.app.FragmentStatePagerAdapter}. <ide> */ <ide> private SectionsPagerAdapter mSectionsPagerAdapter; <ide> <del> /** <del> * The {@link ViewPager} that will host the section contents. <del> */ <add> /** The {@link ViewPager} that will host the section contents. */ <ide> private ViewPager mViewPager; <ide> <ide> @Override <ide> <ide> application = (ScroballApplication) getApplication(); <ide> <del> Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); <add> Toolbar toolbar = findViewById(R.id.toolbar); <ide> setSupportActionBar(toolbar); <ide> // Create the adapter that will return a fragment for each of the three <ide> // primary sections of the activity. <ide> mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); <ide> <ide> // Set up the ViewPager with the sections adapter. <del> mViewPager = (ViewPager) findViewById(R.id.container); <add> mViewPager = findViewById(R.id.container); <ide> mViewPager.setAdapter(mSectionsPagerAdapter); <ide> <del> TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); <add> TabLayout tabLayout = findViewById(R.id.tabs); <ide> tabLayout.setupWithViewPager(mViewPager); <ide> } <del> <ide> <ide> @Override <ide> public boolean onCreateOptionsMenu(Menu menu) { <ide> new AlertDialog.Builder(this) <ide> .setTitle(R.string.are_you_sure) <ide> .setMessage(R.string.logout_confirm) <del> .setPositiveButton(android.R.string.yes, (dialog, whichButton) -> { <del> SharedPreferences preferences = application.getSharedPreferences(); <del> SharedPreferences.Editor editor = preferences.edit(); <del> editor.remove(getString(R.string.saved_session_key)); <del> editor.apply(); <add> .setPositiveButton( <add> android.R.string.yes, <add> (dialog, whichButton) -> { <add> SharedPreferences preferences = application.getSharedPreferences(); <add> SharedPreferences.Editor editor = preferences.edit(); <add> editor.remove(getString(R.string.saved_session_key)); <add> editor.apply(); <ide> <del> application.getScroballDB().clear(); <del> application.getLastfmClient().clearSession(); <add> application.getScroballDB().clear(); <add> application.getLastfmClient().clearSession(); <ide> <del> Intent intent = new Intent(this, SplashScreen.class); <del> intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); <del> startActivity(intent); <del> finish(); <del> }) <del> .setNegativeButton(android.R.string.no, null).show(); <add> Intent intent = new Intent(this, SplashScreen.class); <add> intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); <add> startActivity(intent); <add> finish(); <add> }) <add> .setNegativeButton(android.R.string.no, null) <add> .show(); <ide> } <ide> <ide> /** <del> * A {@link FragmentPagerAdapter} that returns a fragment corresponding to <del> * one of the sections/tabs/pages. <add> * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the <add> * sections/tabs/pages. <ide> */ <ide> public class SectionsPagerAdapter extends FragmentPagerAdapter { <ide> <del> List<Fragment> fragments = ImmutableList.of( <del> new NowPlayingFragment(), new ScrobbleHistoryFragment()); <add> List<Fragment> fragments = <add> ImmutableList.of(new NowPlayingFragment(), new ScrobbleHistoryFragment()); <ide> <ide> public SectionsPagerAdapter(FragmentManager fm) { <ide> super(fm);
Java
lgpl-2.1
1d66bd0c57c3b3a7f36b34ae3a7d931b799d61dc
0
johanneslerch/heros
package heros.ide.edgefunc.fieldsens; import heros.ide.edgefunc.EdgeFunction; import java.util.HashSet; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.Sets; public class OverwriteFunction<Field> extends ChainableEdgeFunction<Field> { private final Set<Field> fields; @SuppressWarnings("unchecked") public OverwriteFunction(Factory<Field> factory, Field field) { super(factory, null); this.fields = Sets.newHashSet(field); } OverwriteFunction(Factory<Field> factory, Set<Field> fields, ChainableEdgeFunction<Field> chainedFunction) { super(factory, chainedFunction); this.fields = fields; } @Override protected boolean mayThisReturnTop() { //If this does not have a preceding function it may return top, e.g., a prepend with the same field may precede in the future. //This overwrite may cause a composition resulting in allTop, but the respective mayReturnTop must be handled //by the succeeding function (e.g., read of overwritten field). //This definition is important to propagate overwrite functions at initial seeds. return chainedFunction == null; } @Override protected AccessPathBundle<Field> _computeTarget(AccessPathBundle<Field> source) { return source.overwrite(fields); } @Override protected EdgeFunction<AccessPathBundle<Field>> _composeWith(ChainableEdgeFunction<Field> chainableFunction) { if (chainableFunction instanceof OverwriteFunction) { OverwriteFunction<Field> overwriteFunction = (OverwriteFunction<Field>) chainableFunction; HashSet<Field> newFields = Sets.newHashSet(fields); newFields.addAll(overwriteFunction.fields); return new OverwriteFunction<Field>(factory, newFields, chainedFunction); } if (chainableFunction instanceof ReadFunction) { if (containsField(((ReadFunction<Field>) chainableFunction).field)) return factory.allTop(); else return chainableFunction.chainIfNotNull(chainedFunction); } return chainableFunction.chain(this); } @Override public ChainableEdgeFunction<Field> chain(ChainableEdgeFunction<Field> f) { return new OverwriteFunction<Field>(factory, fields, f); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fields == null) ? 0 : fields.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; OverwriteFunction other = (OverwriteFunction) obj; if (fields == null) { if (other.fields != null) return false; } else if (!fields.equals(other.fields)) return false; return true; } public boolean containsField(Field field) { for (Field f : fields) if (f.equals(field)) return true; return false; } @Override public String toString() { return "overwrite(" + Joiner.on(",").join(fields) + ")" + super.toString(); } }
src/heros/ide/edgefunc/fieldsens/OverwriteFunction.java
package heros.ide.edgefunc.fieldsens; import heros.ide.edgefunc.EdgeFunction; import java.util.HashSet; import java.util.Set; import com.google.common.base.Joiner; import com.google.common.collect.Sets; public class OverwriteFunction<Field> extends ChainableEdgeFunction<Field> { private final Set<Field> fields; @SuppressWarnings("unchecked") public OverwriteFunction(Factory<Field> factory, Field field) { super(factory, null); this.fields = Sets.newHashSet(field); } OverwriteFunction(Factory<Field> factory, Set<Field> fields, ChainableEdgeFunction<Field> chainedFunction) { super(factory, chainedFunction); this.fields = fields; } @Override protected boolean mayThisReturnTop() { //if this does not have a preceding function it may return top, e.g., a prepend with the same field may precede in the future //o.w. the succeeding function (e.g., read of overwritten field) may return top, but not this overwrite //this definition is important to propagate overwrite functions at initial seeds return chainedFunction == null; } @Override protected AccessPathBundle<Field> _computeTarget(AccessPathBundle<Field> source) { return source.overwrite(fields); } @Override protected EdgeFunction<AccessPathBundle<Field>> _composeWith(ChainableEdgeFunction<Field> chainableFunction) { if (chainableFunction instanceof OverwriteFunction) { OverwriteFunction<Field> overwriteFunction = (OverwriteFunction<Field>) chainableFunction; HashSet<Field> newFields = Sets.newHashSet(fields); newFields.addAll(overwriteFunction.fields); return new OverwriteFunction<Field>(factory, newFields, chainedFunction); } if (chainableFunction instanceof ReadFunction) { if (containsField(((ReadFunction<Field>) chainableFunction).field)) return factory.allTop(); else return chainableFunction.chainIfNotNull(chainedFunction); } return chainableFunction.chain(this); } @Override public ChainableEdgeFunction<Field> chain(ChainableEdgeFunction<Field> f) { return new OverwriteFunction<Field>(factory, fields, f); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((fields == null) ? 0 : fields.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; OverwriteFunction other = (OverwriteFunction) obj; if (fields == null) { if (other.fields != null) return false; } else if (!fields.equals(other.fields)) return false; return true; } public boolean containsField(Field field) { for (Field f : fields) if (f.equals(field)) return true; return false; } @Override public String toString() { return "overwrite(" + Joiner.on(",").join(fields) + ")" + super.toString(); } }
improved/fixed comment
src/heros/ide/edgefunc/fieldsens/OverwriteFunction.java
improved/fixed comment
<ide><path>rc/heros/ide/edgefunc/fieldsens/OverwriteFunction.java <ide> <ide> @Override <ide> protected boolean mayThisReturnTop() { <del> //if this does not have a preceding function it may return top, e.g., a prepend with the same field may precede in the future <del> //o.w. the succeeding function (e.g., read of overwritten field) may return top, but not this overwrite <del> //this definition is important to propagate overwrite functions at initial seeds <add> //If this does not have a preceding function it may return top, e.g., a prepend with the same field may precede in the future. <add> //This overwrite may cause a composition resulting in allTop, but the respective mayReturnTop must be handled <add> //by the succeeding function (e.g., read of overwritten field). <add> //This definition is important to propagate overwrite functions at initial seeds. <ide> return chainedFunction == null; <ide> } <ide>
Java
apache-2.0
error: pathspec 'Android/IrssiNotifier/src/fi/iki/murgo/irssinotifier/MessageGenerator.java' did not match any file(s) known to git
f8e0d1bcc09c0d0d3dfea1688701be7d9eadee7d
1
murgo/IrssiNotifier,murgo/IrssiNotifier,varazir/IrssiNotifier,varazir/IrssiNotifier,varazir/IrssiNotifier,murgo/IrssiNotifier,varazir/IrssiNotifier,murgo/IrssiNotifier
package fi.iki.murgo.irssinotifier; import android.content.Context; import org.json.JSONObject; import java.util.HashMap; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class MessageGenerator extends TimerTask { private static Random random = new Random(); private Context context; public MessageGenerator(Context context) { this.context = context; } public static void Flood(Context context) { new Timer().schedule(new MessageGenerator(context), 5000); } private static String getRandomString(int min, int max) { char[] chars = "ABCDEFHGIJKLMNOPQRSTUVWXYZÅÄÖabcdefghijklmnopqrstuvwxyzåäöABCDEFHGIJKLMNOPQRSTUVWXYZÅÄÖabcdefghijklmnopqrstuvwxyzåäö;:_1234567890+!\"#¤%&/()=?¨'´`^*?-.,<>|\\[]€£$§½µ".toCharArray(); StringBuilder sb = new StringBuilder(); int amount = max <= min ? max : min + random.nextInt(1 + (max - min)); for (int i = 0; i < amount; i++) { sb.append(chars[random.nextInt(chars.length)]); } return sb.toString(); } private static long nextLong(long n) { long bits, val; do { bits = (random.nextLong() << 1) >>> 1; val = bits % n; } while (bits-val+(n-1) < 0L); return val; } @Override public void run() { fillDb(222, 2); sendNotifications(2, 2); this.context = null; } private void fillDb(int channelCount, int messagesPerChannel) { DataAccess dao = new DataAccess(context); for (int i = 0; i < channelCount; i++) { String channel = getRandomString(5, 10); for (int j = 0; j < messagesPerChannel; j++) { System.out.println("DB: Faking message " + j + " of " + messagesPerChannel + " for channel " + i + " of " + channelCount); IrcMessage msg = new IrcMessage(); msg.setChannel(channel); msg.setMessage(getRandomString(2, 30)); msg.setNick(getRandomString(4, 10)); msg.setServerTimestamp(System.currentTimeMillis() - nextLong(1000L * 60 * 60 * 24 * 30)); msg.setExternalId(getRandomString(6, 6)); dao.handleMessage(msg); } } } private void sendNotifications(int channelCount, int messagesPerChannel) { IrcNotificationManager manager = IrcNotificationManager.getInstance(); for (int i = 0; i < channelCount; i++) { String channel = getRandomString(5, 10); for (int j = 0; j < messagesPerChannel; j++) { System.out.println("Notification: Faking message " + j + " of " + messagesPerChannel + " for channel " + i + " of " + channelCount); HashMap<String, String> map = new HashMap<String, String>(); map.put("channel", channel); map.put("message", getRandomString(2, 30)); map.put("nick", getRandomString(4, 10)); map.put("server_timestamp", Double.toString((System.currentTimeMillis() - nextLong(1000L * 60 * 60 * 24 * 30)) / 1000.0)); map.put("id", getRandomString(6, 6)); JSONObject object = new JSONObject(map); manager.handle(context, object.toString()); } } } }
Android/IrssiNotifier/src/fi/iki/murgo/irssinotifier/MessageGenerator.java
ANDROID: Added test message generator
Android/IrssiNotifier/src/fi/iki/murgo/irssinotifier/MessageGenerator.java
ANDROID: Added test message generator
<ide><path>ndroid/IrssiNotifier/src/fi/iki/murgo/irssinotifier/MessageGenerator.java <add>package fi.iki.murgo.irssinotifier; <add> <add>import android.content.Context; <add>import org.json.JSONObject; <add> <add>import java.util.HashMap; <add>import java.util.Random; <add>import java.util.Timer; <add>import java.util.TimerTask; <add> <add>public class MessageGenerator extends TimerTask { <add> <add> private static Random random = new Random(); <add> private Context context; <add> <add> public MessageGenerator(Context context) { <add> this.context = context; <add> } <add> <add> public static void Flood(Context context) { <add> new Timer().schedule(new MessageGenerator(context), 5000); <add> } <add> <add> private static String getRandomString(int min, int max) { <add> char[] chars = "ABCDEFHGIJKLMNOPQRSTUVWXYZÅÄÖabcdefghijklmnopqrstuvwxyzåäöABCDEFHGIJKLMNOPQRSTUVWXYZÅÄÖabcdefghijklmnopqrstuvwxyzåäö;:_1234567890+!\"#¤%&/()=?¨'´`^*?-.,<>|\\[]€£$§½µ".toCharArray(); <add> StringBuilder sb = new StringBuilder(); <add> int amount = max <= min ? max : min + random.nextInt(1 + (max - min)); <add> for (int i = 0; i < amount; i++) { <add> sb.append(chars[random.nextInt(chars.length)]); <add> } <add> return sb.toString(); <add> } <add> <add> private static long nextLong(long n) { <add> long bits, val; <add> do { <add> bits = (random.nextLong() << 1) >>> 1; <add> val = bits % n; <add> } while (bits-val+(n-1) < 0L); <add> return val; <add> } <add> <add> @Override <add> public void run() { <add> fillDb(222, 2); <add> sendNotifications(2, 2); <add> <add> this.context = null; <add> } <add> <add> private void fillDb(int channelCount, int messagesPerChannel) { <add> DataAccess dao = new DataAccess(context); <add> <add> for (int i = 0; i < channelCount; i++) { <add> String channel = getRandomString(5, 10); <add> for (int j = 0; j < messagesPerChannel; j++) { <add> System.out.println("DB: Faking message " + j + " of " + messagesPerChannel + " for channel " + i + " of " + channelCount); <add> <add> IrcMessage msg = new IrcMessage(); <add> msg.setChannel(channel); <add> msg.setMessage(getRandomString(2, 30)); <add> msg.setNick(getRandomString(4, 10)); <add> msg.setServerTimestamp(System.currentTimeMillis() - nextLong(1000L * 60 * 60 * 24 * 30)); <add> msg.setExternalId(getRandomString(6, 6)); <add> <add> dao.handleMessage(msg); <add> } <add> } <add> } <add> <add> private void sendNotifications(int channelCount, int messagesPerChannel) { <add> IrcNotificationManager manager = IrcNotificationManager.getInstance(); <add> <add> for (int i = 0; i < channelCount; i++) { <add> String channel = getRandomString(5, 10); <add> for (int j = 0; j < messagesPerChannel; j++) { <add> System.out.println("Notification: Faking message " + j + " of " + messagesPerChannel + " for channel " + i + " of " + channelCount); <add> HashMap<String, String> map = new HashMap<String, String>(); <add> map.put("channel", channel); <add> map.put("message", getRandomString(2, 30)); <add> map.put("nick", getRandomString(4, 10)); <add> map.put("server_timestamp", Double.toString((System.currentTimeMillis() - nextLong(1000L * 60 * 60 * 24 * 30)) / 1000.0)); <add> map.put("id", getRandomString(6, 6)); <add> JSONObject object = new JSONObject(map); <add> <add> manager.handle(context, object.toString()); <add> } <add> } <add> } <add>}
Java
epl-1.0
dac666a8b94c67ebcce5b01b91348e60535b45c5
0
sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.GridEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListBandEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableCellEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableEditPart; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.jface.action.Action; /** * The factory for creating actions to insert table or list group in the * position */ public class InsertGroupActionFactory { private static InsertPositionGroupAction[] instances = new InsertPositionGroupAction[]{ new InsertAboveGroupAction( null, Messages.getString( "InsertPositionGroupAction.Label.Above" ) ), //$NON-NLS-1$ new InsertBelowGroupAction( null, Messages.getString( "InsertPositionGroupAction.Label.Below" ) ), //$NON-NLS-1$ // new InsertIntoGroupAction( null, // Messages.getString( "InsertPositionGroupAction.Label.Into" ) ) //$NON-NLS-1$ }; /** * Gets actions array * * @param selection * selected editparts * @return actions array */ public static Action[] getInsertGroupActions( List selection ) { initInstances( selection ); return instances; } private static void initInstances( List selection ) { for ( int i = 0; i < instances.length; i++ ) { instances[i].setSelection( selection ); } } } abstract class InsertPositionGroupAction extends Action { private static final String STACK_MSG_ADD_GROUP = Messages.getString( "AddGroupAction.stackMsg.addGroup" ); //$NON-NLS-1$ private Object currentModel; private List selection; protected static final int POSITION_TOP_LEVEL = 0; protected static final int POSITION_INNERMOST = -1; protected InsertPositionGroupAction( List selection, String text ) { super( ); this.selection = selection; setText( text ); } public void setSelection( List selection ) { this.selection = selection; this.currentModel = null; } /* * (non-Javadoc) * * @see org.eclipse.jface.action.Action#isEnabled() */ public boolean isEnabled( ) { return getTableEditPart( ) != null || getListEditPart( ) != null; } /** * Runs action. * */ public void run( ) { CommandStack stack = getActiveCommandStack( ); stack.startTrans( STACK_MSG_ADD_GROUP ); boolean retValue = false; if ( getTableEditPart( ) != null ) { retValue = getTableEditPart( ).insertGroup( getPosition( ) ); } else { retValue = getListEditPart( ).insertGroup( getPosition( ) ); } if ( retValue ) { stack.commit( ); } else { stack.rollbackAll( ); } } protected boolean isGroup( ) { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainer( ) instanceof GroupHandle; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getElemtHandle( ) instanceof GroupHandle; } return false; } /** * Returns if the order is reverse * * @return true when slot is not footer */ protected boolean isNotReverse( ) { if ( currentModel != null ) { if ( isGroup( ) ) { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainerSlotHandle( ) .getSlotID( ) != IGroupElementModel.FOOTER_SLOT; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getSlotId( ) != IGroupElementModel.FOOTER_SLOT; } } else { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainerSlotHandle( ) .getSlotID( ) != TableHandle.FOOTER_SLOT; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getSlotId( ) != ListHandle.FOOTER_SLOT; } } } return true; } /** * Gets table edit part. * * @return The current selected table edit part, null if no table edit part * is selected. */ protected TableEditPart getTableEditPart( ) { if ( getSelection( ) == null || getSelection( ).isEmpty( ) ) return null; List list = getSelection( ); int size = list.size( ); TableEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = getSelection( ).get( i ); if ( i == 0 && obj instanceof ReportElementEditPart ) { currentModel = ( (ReportElementEditPart) obj ).getModel( ); } if ( obj instanceof TableEditPart ) { part = (TableEditPart) obj; break; } else if ( obj instanceof TableCellEditPart ) { part = (TableEditPart) ( (TableCellEditPart) obj ).getParent( ); break; } } //Only table permitted if ( part instanceof GridEditPart ) return null; return part; } /** * Gets list edit part. * * @return The current selected list edit part, null if no list edit part is * selected. */ protected ListEditPart getListEditPart( ) { if ( getSelection( ) == null || getSelection( ).isEmpty( ) ) return null; List list = getSelection( ); int size = list.size( ); ListEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = getSelection( ).get( i ); if ( i == 0 && obj instanceof ReportElementEditPart ) { currentModel = ( (ReportElementEditPart) obj ).getModel( ); } if ( obj instanceof ListEditPart ) { part = (ListEditPart) obj; break; } else if ( obj instanceof ListBandEditPart ) { part = (ListEditPart) ( (ListBandEditPart) obj ).getParent( ); break; } } return part; } public List getSelection( ) { return selection; } protected RowHandle getRowHandle( ) { if ( currentModel instanceof RowHandle ) { return (RowHandle) currentModel; } else if ( currentModel instanceof CellHandle ) { return (RowHandle) ( (CellHandle) currentModel ).getContainer( ); } return null; } protected ListBandProxy getListBandProxy( ) { if ( currentModel instanceof ListBandProxy ) { return (ListBandProxy) currentModel; } return null; } /** * Gets the activity stack of the report * * @return returns the stack */ protected CommandStack getActiveCommandStack( ) { return SessionHandleAdapter.getInstance( ).getCommandStack(); } /** * Returns the current position of the selected part * * @return the current position of the selected part */ protected int getCurrentPosition( ) { if ( currentModel != null && isGroup( ) ) { if ( getRowHandle( ) != null ) { DesignElementHandle group = getRowHandle( ).getContainer( ); TableHandle table = (TableHandle) group.getContainer( ); return DEUtil.findInsertPosition( table.getGroups( ) .getElementHandle( ), group, table.getGroups( ) .getSlotID( ) ); } else if ( getListBandProxy( ) != null ) { DesignElementHandle group = getListBandProxy( ).getElemtHandle( ); ListHandle list = (ListHandle) group.getContainer( ); return DEUtil.findInsertPosition( list.getGroups( ) .getElementHandle( ), group, list.getGroups( ) .getSlotID( ) ); } } return POSITION_INNERMOST; } /** * Returns the insert position * * @return the insert position */ abstract protected int getPosition( ); } class InsertAboveGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertAboveGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { if ( isGroup( ) ) { if ( isNotReverse( ) ) { return getCurrentPosition( ); } return getCurrentPosition( ) + 1; } if ( isNotReverse( ) ) { return POSITION_TOP_LEVEL; } return POSITION_INNERMOST; } } class InsertBelowGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertBelowGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { if ( isGroup( ) ) { if ( isNotReverse( ) ) { return getCurrentPosition( ) + 1; } return getCurrentPosition( ); } if ( isNotReverse( ) ) { return POSITION_INNERMOST; } return POSITION_TOP_LEVEL; } } /** * Insert table or list group in the position */ class InsertIntoGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertIntoGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#isEnabled() */ public boolean isEnabled( ) { return super.isEnabled( ) && isGroup( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { return POSITION_INNERMOST; } }
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/editors/schematic/actions/InsertGroupActionFactory.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.GridEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListBandEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ListEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableCellEditPart; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.TableEditPart; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.jface.action.Action; /** * The factory for creating actions to insert table or list group in the * position */ public class InsertGroupActionFactory { private static InsertPositionGroupAction[] instances = new InsertPositionGroupAction[]{ new InsertAboveGroupAction( null, Messages.getString( "InsertPositionGroupAction.Label.Above" ) ), //$NON-NLS-1$ new InsertBelowGroupAction( null, Messages.getString( "InsertPositionGroupAction.Label.Below" ) ), //$NON-NLS-1$ new InsertIntoGroupAction( null, Messages.getString( "InsertPositionGroupAction.Label.Into" ) ) //$NON-NLS-1$ }; /** * Gets actions array * * @param selection * selected editparts * @return actions array */ public static Action[] getInsertGroupActions( List selection ) { initInstances( selection ); return instances; } private static void initInstances( List selection ) { for ( int i = 0; i < instances.length; i++ ) { instances[i].setSelection( selection ); } } } abstract class InsertPositionGroupAction extends Action { private static final String STACK_MSG_ADD_GROUP = Messages.getString( "AddGroupAction.stackMsg.addGroup" ); //$NON-NLS-1$ private Object currentModel; private List selection; protected static final int POSITION_TOP_LEVEL = 0; protected static final int POSITION_INNERMOST = -1; protected InsertPositionGroupAction( List selection, String text ) { super( ); this.selection = selection; setText( text ); } public void setSelection( List selection ) { this.selection = selection; this.currentModel = null; } /* * (non-Javadoc) * * @see org.eclipse.jface.action.Action#isEnabled() */ public boolean isEnabled( ) { return getTableEditPart( ) != null || getListEditPart( ) != null; } /** * Runs action. * */ public void run( ) { CommandStack stack = getActiveCommandStack( ); stack.startTrans( STACK_MSG_ADD_GROUP ); boolean retValue = false; if ( getTableEditPart( ) != null ) { retValue = getTableEditPart( ).insertGroup( getPosition( ) ); } else { retValue = getListEditPart( ).insertGroup( getPosition( ) ); } if ( retValue ) { stack.commit( ); } else { stack.rollbackAll( ); } } protected boolean isGroup( ) { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainer( ) instanceof GroupHandle; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getElemtHandle( ) instanceof GroupHandle; } return false; } /** * Returns if the order is reverse * * @return true when slot is not footer */ protected boolean isNotReverse( ) { if ( currentModel != null ) { if ( isGroup( ) ) { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainerSlotHandle( ) .getSlotID( ) != IGroupElementModel.FOOTER_SLOT; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getSlotId( ) != IGroupElementModel.FOOTER_SLOT; } } else { if ( getRowHandle( ) != null ) { return getRowHandle( ).getContainerSlotHandle( ) .getSlotID( ) != TableHandle.FOOTER_SLOT; } else if ( getListBandProxy( ) != null ) { return getListBandProxy( ).getSlotId( ) != ListHandle.FOOTER_SLOT; } } } return true; } /** * Gets table edit part. * * @return The current selected table edit part, null if no table edit part * is selected. */ protected TableEditPart getTableEditPart( ) { if ( getSelection( ) == null || getSelection( ).isEmpty( ) ) return null; List list = getSelection( ); int size = list.size( ); TableEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = getSelection( ).get( i ); if ( i == 0 && obj instanceof ReportElementEditPart ) { currentModel = ( (ReportElementEditPart) obj ).getModel( ); } if ( obj instanceof TableEditPart ) { part = (TableEditPart) obj; break; } else if ( obj instanceof TableCellEditPart ) { part = (TableEditPart) ( (TableCellEditPart) obj ).getParent( ); break; } } //Only table permitted if ( part instanceof GridEditPart ) return null; return part; } /** * Gets list edit part. * * @return The current selected list edit part, null if no list edit part is * selected. */ protected ListEditPart getListEditPart( ) { if ( getSelection( ) == null || getSelection( ).isEmpty( ) ) return null; List list = getSelection( ); int size = list.size( ); ListEditPart part = null; for ( int i = 0; i < size; i++ ) { Object obj = getSelection( ).get( i ); if ( i == 0 && obj instanceof ReportElementEditPart ) { currentModel = ( (ReportElementEditPart) obj ).getModel( ); } if ( obj instanceof ListEditPart ) { part = (ListEditPart) obj; break; } else if ( obj instanceof ListBandEditPart ) { part = (ListEditPart) ( (ListBandEditPart) obj ).getParent( ); break; } } return part; } public List getSelection( ) { return selection; } protected RowHandle getRowHandle( ) { if ( currentModel instanceof RowHandle ) { return (RowHandle) currentModel; } else if ( currentModel instanceof CellHandle ) { return (RowHandle) ( (CellHandle) currentModel ).getContainer( ); } return null; } protected ListBandProxy getListBandProxy( ) { if ( currentModel instanceof ListBandProxy ) { return (ListBandProxy) currentModel; } return null; } /** * Gets the activity stack of the report * * @return returns the stack */ protected CommandStack getActiveCommandStack( ) { return SessionHandleAdapter.getInstance( ).getCommandStack(); } /** * Returns the current position of the selected part * * @return the current position of the selected part */ protected int getCurrentPosition( ) { if ( currentModel != null && isGroup( ) ) { if ( getRowHandle( ) != null ) { DesignElementHandle group = getRowHandle( ).getContainer( ); TableHandle table = (TableHandle) group.getContainer( ); return DEUtil.findInsertPosition( table.getGroups( ) .getElementHandle( ), group, table.getGroups( ) .getSlotID( ) ); } else if ( getListBandProxy( ) != null ) { DesignElementHandle group = getListBandProxy( ).getElemtHandle( ); ListHandle list = (ListHandle) group.getContainer( ); return DEUtil.findInsertPosition( list.getGroups( ) .getElementHandle( ), group, list.getGroups( ) .getSlotID( ) ); } } return POSITION_INNERMOST; } /** * Returns the insert position * * @return the insert position */ abstract protected int getPosition( ); } class InsertAboveGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertAboveGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { if ( isGroup( ) ) { if ( isNotReverse( ) ) { return getCurrentPosition( ); } return getCurrentPosition( ) + 1; } if ( isNotReverse( ) ) { return POSITION_TOP_LEVEL; } return POSITION_INNERMOST; } } class InsertBelowGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertBelowGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { if ( isGroup( ) ) { if ( isNotReverse( ) ) { return getCurrentPosition( ) + 1; } return getCurrentPosition( ); } if ( isNotReverse( ) ) { return POSITION_INNERMOST; } return POSITION_TOP_LEVEL; } } /** * Insert table or list group in the position */ class InsertIntoGroupAction extends InsertPositionGroupAction { /** * @param editParts */ public InsertIntoGroupAction( List editParts, String text ) { super( editParts, text ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#isEnabled() */ public boolean isEnabled( ) { return super.isEnabled( ) && isGroup( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.InsertPositionGroupAction#getPosition() */ protected int getPosition( ) { return POSITION_INNERMOST; } }
- SCR(s) Resolved: 78150 - Description: Insert group option for a group has confusing "into" option - Regression ( Yes/No ):No - Code Owner: Yulin Wang - Code Reviewers: GUI members - Tests: Local test. - Test Automated: No, GUI feature - Case Entries Resolved: None - Notes to Developers: None - Notes to QA: None - Notes to Documentation: None - Notes to Configuration Management: None - Notes to Support: None - Notes to Product Marketing: None
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/editors/schematic/actions/InsertGroupActionFactory.java
- SCR(s) Resolved: 78150
<ide><path>I/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/editors/schematic/actions/InsertGroupActionFactory.java <ide> Messages.getString( "InsertPositionGroupAction.Label.Above" ) ), //$NON-NLS-1$ <ide> new InsertBelowGroupAction( null, <ide> Messages.getString( "InsertPositionGroupAction.Label.Below" ) ), //$NON-NLS-1$ <del> new InsertIntoGroupAction( null, <del> Messages.getString( "InsertPositionGroupAction.Label.Into" ) ) //$NON-NLS-1$ <add>// new InsertIntoGroupAction( null, <add>// Messages.getString( "InsertPositionGroupAction.Label.Into" ) ) //$NON-NLS-1$ <ide> }; <ide> <ide> /**
Java
apache-2.0
c2aea2706567cdae0a128074ac84cfb457d49f8b
0
jackmiras/placeholderj
package com.example.jackmiras.placeholderj.managers; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.jackmiras.placeholderj.R; import retrofit.RetrofitError; /** * Created by jackmiras on 03/10/15. */ public class PlaceHolderManager { private View viewContainer = null; private View framelayoutViewLoading = null; private ViewGroup linearlayoutViewEmpty = null; private TextView textViewEmptyMessage; private TextView textViewEmptyTryAgain = null; private ViewGroup linearlayoutViewError = null; private ImageView imageViewErrorIcon = null; private TextView textViewErrorMessage = null; private TextView textViewErrorTryAgain = null; private boolean isLoadingViewBeingShown; private boolean isErrorViewBeingShown; private boolean isEmptyViewBeingShown; public PlaceHolderManager(Activity activity, int... viewsId) { this(activity.getWindow().getDecorView(), viewsId); } public PlaceHolderManager(View view, int... viewsId) { for (int index = 0; index < viewsId.length; index++) { if (viewsId[index] == R.id.framelayout_view_loading) { linearlayoutViewError = (ViewGroup) view.findViewById(R.id.framelayout_view_loading); } else if (viewsId[index] == R.id.linearlayout_view_empty) { framelayoutViewLoading = view.findViewById(R.id.linearlayout_view_empty); textViewEmptyMessage = (TextView) view.findViewById(R.id.textview_empty_message); textViewEmptyTryAgain = (TextView) view.findViewById(R.id.textview_empty_try_again); } else if (viewsId[index] == R.id.linearlayout_view_error) { linearlayoutViewEmpty = (ViewGroup) view.findViewById(R.id.linearlayout_view_error); imageViewErrorIcon = (ImageView) view.findViewById(R.id.imageview_error_icon); textViewErrorMessage = (TextView) view.findViewById(R.id.textview_error_message); textViewErrorTryAgain = (TextView) view.findViewById(R.id.textview_error_try_again); } else { viewContainer = view.findViewById(viewsId[index]); } } } private void setViewVisibility(View view, int visibility) { if (view != null) view.setVisibility(visibility); } public void showLoading() { isLoadingViewBeingShown = true; changeViewsVisibility(); setViewVisibility(framelayoutViewLoading, View.VISIBLE); } public void showEmpty(int messageRes, RetrofitError error, View.OnClickListener callback) { textViewEmptyMessage.setText(messageRes); showEmpty(error, callback); } public void showEmpty(RetrofitError error, View.OnClickListener callback) { isEmptyViewBeingShown = true; changeViewsVisibility(); if (error == null && textViewEmptyTryAgain.getVisibility() == View.VISIBLE) { textViewEmptyTryAgain.setVisibility(View.GONE); } else { textViewEmptyTryAgain.setVisibility(View.VISIBLE); textViewEmptyTryAgain.setOnClickListener(callback); } setViewVisibility(linearlayoutViewEmpty, View.VISIBLE); } public void showError(RetrofitError error, View.OnClickListener callback) { isErrorViewBeingShown = true; changeViewsVisibility(); if (error != null && error.getKind() == RetrofitError.Kind.NETWORK) { imageViewErrorIcon.setImageResource(R.drawable.icon_error_network); textViewErrorMessage.setText(R.string.global_network_error); } else { imageViewErrorIcon.setImageResource(R.drawable.icon_error_unknown); textViewErrorMessage.setText(R.string.global_unknown_error); } textViewErrorTryAgain.setOnClickListener(callback); setViewVisibility(linearlayoutViewError, View.VISIBLE); } public void hideLoading() { isLoadingViewBeingShown = false; changeViewsVisibility(); setViewVisibility(framelayoutViewLoading, View.GONE); } public void hideEmpty() { isEmptyViewBeingShown = false; changeViewsVisibility(); setViewVisibility(linearlayoutViewEmpty, View.GONE); } public void hideError() { isErrorViewBeingShown = false; changeViewsVisibility(); setViewVisibility(linearlayoutViewError, View.GONE); } public void changeViewsVisibility() { if (!isLoadingViewBeingShown) setViewVisibility(framelayoutViewLoading, View.GONE); if (!isEmptyViewBeingShown) setViewVisibility(linearlayoutViewEmpty, View.GONE); if (!isEmptyViewBeingShown) setViewVisibility(linearlayoutViewError, View.GONE); if (isLoadingViewBeingShown || isEmptyViewBeingShown || isErrorViewBeingShown) setViewVisibility(viewContainer, View.GONE); if (!isLoadingViewBeingShown && !isEmptyViewBeingShown && !isErrorViewBeingShown) setViewVisibility(viewContainer, View.VISIBLE); } }
placeholderj/src/main/java/com/example/jackmiras/placeholderj/managers/PlaceHolderManager.java
package com.example.jackmiras.placeholderj.managers; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.jackmiras.placeholderj.R; import com.example.jackmiras.placeholderj.enums.PlaceHolderType; import retrofit.RetrofitError; /** * Created by jackmiras on 03/10/15. */ public class PlaceHolderManager { private View viewContainer = null; private View framelayoutViewLoading = null; private ViewGroup linearlayoutViewEmpty = null; private TextView textViewEmptyMessage; private TextView textViewEmptyTryAgain = null; private ViewGroup linearlayoutViewError = null; private ImageView imageViewErrorIcon = null; private TextView textViewErrorMessage = null; private TextView textViewErrorTryAgain = null; private boolean isLoadingViewBeingShown; private boolean isErrorViewBeingShown; private boolean isEmptyViewBeingShown; public PlaceHolderManager(Activity activity, int viewContainerId, int viewId, PlaceHolderType type) { this(activity.getWindow().getDecorView(), viewContainerId, viewId, type); } public PlaceHolderManager(View view, int viewContainerId, int viewId, PlaceHolderType type) { switch (type) { case LOADING: setup(view, viewContainerId, viewId, 0, 0); break; case EMPTY: setup(view, viewContainerId, 0, viewId, 0); break; case ERROR: setup(view, viewContainerId, 0, 0, viewId); break; } } public PlaceHolderManager(Activity activity, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { this(activity.getWindow().getDecorView(), viewContainerId, loadingViewId, emptyTextId, errorViewId); } public PlaceHolderManager(View view, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { setup(view, viewContainerId, loadingViewId, emptyTextId, errorViewId); } public void setup(View view, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { if (viewContainerId != 0) viewContainer = view.findViewById(viewContainerId); if (loadingViewId != 0) framelayoutViewLoading = view.findViewById(loadingViewId); if (emptyTextId != 0) { linearlayoutViewEmpty = (ViewGroup) view.findViewById(emptyTextId); textViewEmptyMessage = (TextView) view.findViewById(R.id.textview_empty_message); textViewEmptyTryAgain = (TextView) view.findViewById(R.id.textview_empty_try_again); } if (errorViewId != 0) { linearlayoutViewError = (ViewGroup) view.findViewById(errorViewId); imageViewErrorIcon = (ImageView) view.findViewById(R.id.imageview_error_icon); textViewErrorMessage = (TextView) view.findViewById(R.id.textview_error_message); textViewErrorTryAgain = (TextView) view.findViewById(R.id.textview_error_try_again); } } private void setViewVisibility(View view, int visibility) { if (view != null) view.setVisibility(visibility); } public void showLoading() { isLoadingViewBeingShown = true; changeViewsVisibility(); setViewVisibility(framelayoutViewLoading, View.VISIBLE); } public void showEmpty(int messageRes, RetrofitError error, View.OnClickListener callback) { textViewEmptyMessage.setText(messageRes); showEmpty(error, callback); } public void showEmpty(RetrofitError error, View.OnClickListener callback) { isEmptyViewBeingShown = true; changeViewsVisibility(); if (error == null && textViewEmptyTryAgain.getVisibility() == View.VISIBLE) { textViewEmptyTryAgain.setVisibility(View.GONE); } else { textViewEmptyTryAgain.setVisibility(View.VISIBLE); textViewEmptyTryAgain.setOnClickListener(callback); } setViewVisibility(linearlayoutViewEmpty, View.VISIBLE); } public void showError(RetrofitError error, View.OnClickListener callback) { isErrorViewBeingShown = true; changeViewsVisibility(); if (error != null && error.getKind() == RetrofitError.Kind.NETWORK) { imageViewErrorIcon.setImageResource(R.drawable.icon_error_network); textViewErrorMessage.setText(R.string.global_network_error); } else { imageViewErrorIcon.setImageResource(R.drawable.icon_error_unknown); textViewErrorMessage.setText(R.string.global_unknown_error); } textViewErrorTryAgain.setOnClickListener(callback); setViewVisibility(linearlayoutViewError, View.VISIBLE); } public void hideLoading() { isLoadingViewBeingShown = false; changeViewsVisibility(); setViewVisibility(framelayoutViewLoading, View.GONE); } public void hideEmpty() { isEmptyViewBeingShown = false; changeViewsVisibility(); setViewVisibility(linearlayoutViewEmpty, View.GONE); } public void hideError() { isErrorViewBeingShown = false; changeViewsVisibility(); setViewVisibility(linearlayoutViewError, View.GONE); } public void changeViewsVisibility() { if (!isLoadingViewBeingShown) setViewVisibility(framelayoutViewLoading, View.GONE); if (!isEmptyViewBeingShown) setViewVisibility(linearlayoutViewEmpty, View.GONE); if (!isEmptyViewBeingShown) setViewVisibility(linearlayoutViewError, View.GONE); if (isLoadingViewBeingShown || isEmptyViewBeingShown || isErrorViewBeingShown) setViewVisibility(viewContainer, View.GONE); if (!isLoadingViewBeingShown && !isEmptyViewBeingShown && !isErrorViewBeingShown) setViewVisibility(viewContainer, View.VISIBLE); } }
Optimizing the PlaceHolderManager.java to receive a limited number of arguments
placeholderj/src/main/java/com/example/jackmiras/placeholderj/managers/PlaceHolderManager.java
Optimizing the PlaceHolderManager.java to receive a limited number of arguments
<ide><path>laceholderj/src/main/java/com/example/jackmiras/placeholderj/managers/PlaceHolderManager.java <ide> import android.widget.TextView; <ide> <ide> import com.example.jackmiras.placeholderj.R; <del>import com.example.jackmiras.placeholderj.enums.PlaceHolderType; <ide> <ide> import retrofit.RetrofitError; <ide> <ide> private boolean isEmptyViewBeingShown; <ide> <ide> <del> public PlaceHolderManager(Activity activity, int viewContainerId, int viewId, PlaceHolderType type) { <del> this(activity.getWindow().getDecorView(), viewContainerId, viewId, type); <add> public PlaceHolderManager(Activity activity, int... viewsId) { <add> this(activity.getWindow().getDecorView(), viewsId); <ide> } <ide> <del> public PlaceHolderManager(View view, int viewContainerId, int viewId, PlaceHolderType type) { <del> switch (type) { <del> case LOADING: <del> setup(view, viewContainerId, viewId, 0, 0); <del> break; <del> case EMPTY: <del> setup(view, viewContainerId, 0, viewId, 0); <del> break; <del> case ERROR: <del> setup(view, viewContainerId, 0, 0, viewId); <del> break; <del> } <del> } <del> <del> public PlaceHolderManager(Activity activity, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { <del> this(activity.getWindow().getDecorView(), viewContainerId, loadingViewId, emptyTextId, errorViewId); <del> } <del> <del> public PlaceHolderManager(View view, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { <del> setup(view, viewContainerId, loadingViewId, emptyTextId, errorViewId); <del> } <del> <del> public void setup(View view, int viewContainerId, int loadingViewId, int emptyTextId, int errorViewId) { <del> if (viewContainerId != 0) <del> viewContainer = view.findViewById(viewContainerId); <del> if (loadingViewId != 0) <del> framelayoutViewLoading = view.findViewById(loadingViewId); <del> if (emptyTextId != 0) { <del> linearlayoutViewEmpty = (ViewGroup) view.findViewById(emptyTextId); <del> textViewEmptyMessage = (TextView) view.findViewById(R.id.textview_empty_message); <del> textViewEmptyTryAgain = (TextView) view.findViewById(R.id.textview_empty_try_again); <del> } <del> if (errorViewId != 0) { <del> linearlayoutViewError = (ViewGroup) view.findViewById(errorViewId); <del> imageViewErrorIcon = (ImageView) view.findViewById(R.id.imageview_error_icon); <del> textViewErrorMessage = (TextView) view.findViewById(R.id.textview_error_message); <del> textViewErrorTryAgain = (TextView) view.findViewById(R.id.textview_error_try_again); <add> public PlaceHolderManager(View view, int... viewsId) { <add> for (int index = 0; index < viewsId.length; index++) { <add> if (viewsId[index] == R.id.framelayout_view_loading) { <add> linearlayoutViewError = (ViewGroup) view.findViewById(R.id.framelayout_view_loading); <add> } else if (viewsId[index] == R.id.linearlayout_view_empty) { <add> framelayoutViewLoading = view.findViewById(R.id.linearlayout_view_empty); <add> textViewEmptyMessage = (TextView) view.findViewById(R.id.textview_empty_message); <add> textViewEmptyTryAgain = (TextView) view.findViewById(R.id.textview_empty_try_again); <add> } else if (viewsId[index] == R.id.linearlayout_view_error) { <add> linearlayoutViewEmpty = (ViewGroup) view.findViewById(R.id.linearlayout_view_error); <add> imageViewErrorIcon = (ImageView) view.findViewById(R.id.imageview_error_icon); <add> textViewErrorMessage = (TextView) view.findViewById(R.id.textview_error_message); <add> textViewErrorTryAgain = (TextView) view.findViewById(R.id.textview_error_try_again); <add> } else { <add> viewContainer = view.findViewById(viewsId[index]); <add> } <ide> } <ide> } <ide>
JavaScript
mit
6e1d5b174452adb137a743db886f698af1bd591e
0
Squishymedia/bids-validator,nellh/bids-validator,Squishymedia/BIDS-Validator,nellh/bids-validator,nellh/bids-validator
/** * Issues * * A list of all possible issues organized by * issue code and including severity and reason * agnostic to file specifics. */ module.exports = { 0: { key: 'INTERNAL ERROR', severity: 'error', reason: 'Internal error. SOME VALIDATION STEPS MAY NOT HAVE OCCURRED', }, 1: { key: 'NOT_INCLUDED', severity: 'error', reason: 'Files with such naming scheme are not part of BIDS specification. This error is most commonly ' + 'caused by typos in file names that make them not BIDS compatible. Please consult the specification and ' + 'make sure your files are named correctly. If this is not a file naming issue (for example when including ' + 'files not yet covered by the BIDS specification) you should include a ".bidsignore" file in your dataset (see' + ' https://github.com/bids-standard/bids-validator#bidsignore for details). Please ' + 'note that derived (processed) data should be placed in /derivatives folder and source data (such as DICOMS ' + 'or behavioural logs in proprietary formats) should be placed in the /sourcedata folder.', }, 2: { key: 'REPETITION_TIME_GREATER_THAN', severity: 'warning', reason: "'RepetitionTime' is greater than 100 are you sure it's expressed in seconds?", }, 3: { key: 'ECHO_TIME_GREATER_THAN', severity: 'warning', reason: "'EchoTime' is greater than 1 are you sure it's expressed in seconds?", }, 4: { key: 'ECHO_TIME_DIFFERENCE_GREATER_THAN', severity: 'warning', reason: "'EchoTimeDifference' is greater than 1 are you sure it's expressed in seconds?", }, 5: { key: 'TOTAL_READOUT_TIME_GREATER_THAN', severity: 'warning', reason: "'TotalReadoutTime' is greater than 10 are you sure it's expressed in seconds?", }, 6: { key: 'ECHO_TIME_NOT_DEFINED', severity: 'warning', reason: "You should define 'EchoTime' for this file. If you don't provide this information field map correction will not be possible.", }, 7: { key: 'PHASE_ENCODING_DIRECTION_NOT_DEFINED', severity: 'warning', reason: "You should define 'PhaseEncodingDirection' for this file. If you don't provide this information field map correction will not be possible.", }, 8: { key: 'EFFECTIVE_ECHO_SPACING_NOT_DEFINED', severity: 'warning', reason: "You should define 'EffectiveEchoSpacing' for this file. If you don't provide this information field map correction will not be possible.", }, 9: { key: 'TOTAL_READOUT_TIME_NOT_DEFINED', severity: 'warning', reason: "You should define 'TotalReadoutTime' for this file. If you don't provide this information field map correction using TOPUP might not be possible.", }, 10: { key: 'REPETITION_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'RepetitionTime' for this file.", }, 11: { key: 'REPETITION_TIME_UNITS', severity: 'error', reason: "Repetition time was not defined in seconds, milliseconds or microseconds in the scan's header.", }, 12: { key: 'REPETITION_TIME_MISMATCH', severity: 'error', reason: "Repetition time did not match between the scan's header and the associated JSON metadata file.", }, 13: { key: 'SLICE_TIMING_NOT_DEFINED', severity: 'warning', reason: "You should define 'SliceTiming' for this file. If you don't provide this information slice time correction will not be possible.", }, 15: { key: 'ECHO_TIME1-2_NOT_DEFINED', severity: 'error', reason: "You have to define 'EchoTime1' and 'EchoTime2' for this file.", }, 16: { key: 'ECHO_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'EchoTime' for this file.", }, 17: { key: 'UNITS_MUST_DEFINE', severity: 'error', reason: "You have to define 'Units' for this file.", }, 18: { key: 'PHASE_ENCODING_DIRECTION_MUST_DEFINE', severity: 'error', reason: "You have to define 'PhaseEncodingDirection' for this file.", }, 19: { key: 'TOTAL_READOUT_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'TotalReadoutTime' for this file.", }, 20: { key: 'EVENTS_COLUMN_ONSET', severity: 'error', reason: "First column of the events file must be named 'onset'", }, 21: { key: 'EVENTS_COLUMN_DURATION', severity: 'error', reason: "Second column of the events file must be named 'duration'", }, 22: { key: 'TSV_EQUAL_ROWS', severity: 'error', reason: 'All rows must have the same number of columns as there are headers.', }, 23: { key: 'TSV_EMPTY_CELL', severity: 'error', reason: 'Empty cell in TSV file detected: The proper way of labeling missing values is "n/a".', }, 24: { key: 'TSV_IMPROPER_NA', severity: 'warning', reason: 'A proper way of labeling missing values is "n/a".', }, 25: { key: 'EVENTS_TSV_MISSING', severity: 'warning', reason: 'Task scans should have a corresponding events.tsv file. If this is a resting state scan you can ignore this warning or rename the task to include the word "rest".', }, 26: { key: 'NIFTI_HEADER_UNREADABLE', severity: 'error', reason: 'We were unable to parse header data from this NIfTI file. Please ensure it is not corrupted or mislabeled.', }, 27: { key: 'JSON_INVALID', severity: 'error', reason: 'Not a valid JSON file.', }, 28: { key: 'GZ_NOT_GZIPPED', severity: 'error', reason: 'This file ends in the .gz extension but is not actually gzipped.', }, 29: { key: 'VOLUME_COUNT_MISMATCH', severity: 'error', reason: 'The number of volumes in this scan does not match the number of volumes in the corresponding .bvec and .bval files.', }, 30: { key: 'BVAL_MULTIPLE_ROWS', severity: 'error', reason: '.bval files should contain exactly one row of volumes.', }, 31: { key: 'BVEC_NUMBER_ROWS', severity: 'error', reason: '.bvec files should contain exactly three rows of volumes.', }, 32: { key: 'DWI_MISSING_BVEC', severity: 'error', reason: 'DWI scans should have a corresponding .bvec file.', }, 33: { key: 'DWI_MISSING_BVAL', severity: 'error', reason: 'DWI scans should have a corresponding .bval file.', }, 36: { key: 'NIFTI_TOO_SMALL', severity: 'error', reason: 'This file is too small to contain the minimal NIfTI header.', }, 37: { key: 'INTENDED_FOR', severity: 'error', reason: "'IntendedFor' field needs to point to an existing file.", }, 38: { key: 'INCONSISTENT_SUBJECTS', severity: 'warning', reason: 'Not all subjects contain the same files. Each subject should contain the same number of files with ' + 'the same naming unless some files are known to be missing.', }, 39: { key: 'INCONSISTENT_PARAMETERS', severity: 'warning', reason: 'Not all subjects/sessions/runs have the same scanning parameters.', }, 40: { key: 'NIFTI_DIMENSION', severity: 'warning', reason: "Nifti file's header field for dimension information blank or too short.", }, 41: { key: 'NIFTI_UNIT', severity: 'warning', reason: "Nifti file's header field for unit information for x, y, z, and t dimensions empty or too short", }, 42: { key: 'NIFTI_PIXDIM', severity: 'warning', reason: "Nifti file's header field for pixel dimension information empty or too short.", }, 43: { key: 'ORPHANED_SYMLINK', severity: 'error', reason: 'This file appears to be an orphaned symlink. Make sure it correctly points to its referent.', }, 44: { key: 'FILE_READ', severity: 'error', reason: 'We were unable to read this file. Make sure it is not corrupted, incorrectly named or incorrectly symlinked.', }, 45: { key: 'SUBJECT_FOLDERS', severity: 'error', reason: 'There are no subject folders (labeled "sub-*") in the root of this dataset.', }, 46: { key: 'BVEC_ROW_LENGTH', severity: 'error', reason: 'Each row in a .bvec file should contain the same number of values.', }, 47: { key: 'B_FILE', severity: 'error', reason: '.bval and .bvec files must be single space delimited and contain only numerical values.', }, 48: { key: 'PARTICIPANT_ID_COLUMN', severity: 'error', reason: "Participants and phenotype .tsv files must have a 'participant_id' column.", }, 49: { key: 'PARTICIPANT_ID_MISMATCH', severity: 'error', reason: 'Participant labels found in this dataset did not match the values in participant_id column found in the participants.tsv file.', }, 50: { key: 'TASK_NAME_MUST_DEFINE', severity: 'error', reason: "You have to define 'TaskName' for this file.", }, 51: { key: 'PHENOTYPE_SUBJECTS_MISSING', severity: 'error', reason: 'A phenotype/ .tsv file lists subjects that were not found in the dataset.', }, 52: { key: 'STIMULUS_FILE_MISSING', severity: 'error', reason: 'A stimulus file was declared but not found in the dataset.', }, 53: { key: 'NO_T1W', severity: 'ignore', reason: 'Dataset does not contain any T1w scans.', }, 54: { key: 'BOLD_NOT_4D', severity: 'error', reason: 'Bold scans must be 4 dimensional.', }, 55: { key: 'JSON_SCHEMA_VALIDATION_ERROR', severity: 'error', reason: 'Invalid JSON file. The file is not formatted according the schema.', }, 56: { key: 'Participants age 89 or higher', severity: 'warning', reason: 'As per section 164.514(C) of "The De-identification Standard" under HIPAA guidelines, participants with age 89 or higher should be tagged as 89+. More information can be found at https://www.hhs.gov/hipaa/for-professionals/privacy/special-topics/de-identification/#standard', }, 57: { key: 'DATASET_DESCRIPTION_JSON_MISSING', severity: 'error', reason: 'The compulsory file /dataset_description.json is missing. See Section 8.1 of the BIDS specification.', }, 58: { key: 'TASK_NAME_CONTAIN_ILLEGAL_CHARACTER', severity: 'error', reason: 'Task Name contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 59: { key: 'ACQ_NAME_CONTAIN_ILLEGAL_CHARACTER', severity: 'error', reason: 'acq Name contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 60: { key: 'SFORM_AND_QFORM_IN_IMAGE_HEADER_ARE_ZERO', severity: 'error', reason: 'sform_code and qform_code in the image header are 0. The image/file will be considered invalid or assumed to be in LAS orientation.', }, 61: { key: 'QUICK_VALIDATION_FAILED', severity: 'error', reason: 'Quick validation failed - the general folder structure does not resemble a BIDS dataset. Have you chosen the right folder (with "sub-*/" subfolders)? Check for structural/naming issues and presence of at least one subject.', }, 62: { key: 'SUBJECT_VALUE_CONTAINS_ILLEGAL_CHARECTER', severity: 'error', reason: 'Sub label contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 63: { key: 'SESSION_VALUE_CONTAINS_ILLEGAL_CHARECTER', severity: 'error', reason: 'Ses label contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 64: { key: 'SUBJECT_LABEL_IN_FILENAME_DOESNOT_MATCH_DIRECTORY', severity: 'error', reason: "Subject label in the filename doesn't match with the path of the file. File seems to be saved in incorrect subject directory.", }, 65: { key: 'SESSION_LABEL_IN_FILENAME_DOESNOT_MATCH_DIRECTORY', severity: 'error', reason: "Session label in the filename doesn't match with the path of the file. File seems to be saved in incorrect session directory.", }, 66: { key: 'SLICETIMING_VALUES_GREATOR_THAN_REPETITION_TIME', severity: 'error', reason: '"SliceTiming" value/s contains invalid value as it is greater than RepetitionTime. SliceTiming values should be in seconds not milliseconds (common mistake).', }, 67: { key: 'NO_VALID_DATA_FOUND_FOR_SUBJECT', severity: 'error', reason: 'No BIDS compatible data found for at least one subject.', }, 68: { key: 'FILENAME_COLUMN', severity: 'error', reason: "_scans.tsv files must have a 'filename' column.", }, 70: { key: 'WRONG_NEW_LINE', severity: 'error', reason: "All TSV files must use Line Feed '\\n' characters to denote new lines. This files uses Carriage Return '\\r'.", }, 71: { key: 'MISSING_TSV_COLUMN_CHANNELS', severity: 'error', reason: "The column names of the channels file must begin with ['name', 'type', 'units']", }, 72: { key: 'MISSING_TSV_COLUMN_IEEG_CHANNELS', severity: 'error', reason: "The column names of the channels file must begin with ['name', 'type', 'units', 'sampling_frequency', 'low_cutoff', 'high_cutoff', 'notch', 'reference']", }, 73: { key: 'MISSING_TSV_COLUMN_IEEG_ELECTRODES', severity: 'error', reason: "The column names of the electrodes file must begin with ['name', 'x', 'y', 'z', 'size', 'type']", }, 74: { key: 'DUPLICATE_NIFTI_FILES', severity: 'error', reason: "Nifti file exist with both '.nii' and '.nii.gz' extensions.", }, 75: { key: 'NIFTI_PIXDIM4', severity: 'error', reason: "Nifti file's header is missing time dimension information.", }, 76: { key: 'EFFECTIVEECHOSPACING_TOO_LARGE', severity: 'error', reason: "Abnormally high value of 'EffectiveEchoSpacing'.", }, 77: { key: 'UNUSED_STIMULUS', severity: 'warning', reason: 'There are files in the /stimuli directory that are not utilized in any _events.tsv file.', }, 78: { key: 'CHANNELS_COLUMN_SFREQ', severity: 'error', reason: "Fourth column of the channels file must be named 'sampling_frequency'", }, 79: { key: 'CHANNELS_COLUMN_LOWCUT', severity: 'error', reason: "Third column of the channels file must be named 'low_cutoff'", }, 80: { key: 'CHANNELS_COLUMN_HIGHCUT', severity: 'error', reason: "Third column of the channels file must be named 'high_cutoff'", }, 81: { key: 'CHANNELS_COLUMN_NOTCH', severity: 'error', reason: "Third column of the channels file must be named 'notch'", }, 82: { key: 'CUSTOM_COLUMN_WITHOUT_DESCRIPTION', severity: 'warning', reason: 'Tabular file contains custom columns not described in a data dictionary', }, 83: { key: 'ECHOTIME1_2_DIFFERENCE_UNREASONABLE', severity: 'error', reason: 'The value of (EchoTime2 - EchoTime1) should be within the range of 0.0001 - 0.01.', }, 84: { key: 'ACQTIME_FMT', severity: 'error', reason: 'Entries in the "acq_time" column of _scans.tsv should be expressed in the following format YYYY-MM-DDTHH:mm:ss (year, month, day, hour (24h), minute, second; this is equivalent to the RFC3339 “date-time” format. ', }, 85: { key: 'SUSPICIOUSLY_LONG_EVENT_DESIGN', severity: 'warning', reason: 'The onset of the last event is after the total duration of the corresponding scan. This design is suspiciously long. ', }, 86: { key: 'SUSPICIOUSLY_SHORT_EVENT_DESIGN', severity: 'warning', reason: 'The onset of the last event is less than half the total duration of the corresponding scan. This design is suspiciously short. ', }, 87: { key: 'SLICETIMING_ELEMENTS', severity: 'warning', reason: "The number of elements in the SliceTiming array should match the 'k' dimension of the corresponding nifti volume.", }, 88: { key: 'MALFORMED_BVEC', severity: 'error', reason: 'The contents of this .bvec file are undefined or severely malformed. ', }, 89: { key: 'MALFORMED_BVAL', severity: 'error', reason: 'The contents of this .bval file are undefined or severely malformed. ', }, 90: { key: 'SIDECAR_WITHOUT_DATAFILE', severity: 'error', reason: 'A json sidecar file was found without a corresponding data file', }, 91: { key: '_FIELDMAP_WITHOUT_MAGNITUDE_FILE', severity: 'error', reason: '_fieldmap.nii[.gz] file does not have accompanying _magnitude.nii[.gz] file. ', }, 92: { key: 'MISSING_MAGNITUDE1_FILE', severity: 'warning', reason: 'Each _phasediff.nii[.gz] file should be associated with a _magnitude1.nii[.gz] file.', }, 93: { key: 'EFFECTIVEECHOSPACING_LARGER_THAN_TOTALREADOUTTIME', severity: 'error', reason: 'EffectiveEchoSpacing should always be smaller than TotalReadoutTime. ', }, 94: { key: 'MAGNITUDE_FILE_WITH_TOO_MANY_DIMENSIONS', severity: 'error', reason: '_magnitude1.nii[.gz] and _magnitude2.nii[.gz] files must have exactly three dimensions. ', }, 95: { key: 'T1W_FILE_WITH_TOO_MANY_DIMENSIONS', severity: 'error', reason: '_T1w.nii[.gz] files must have exactly three dimensions. ', }, 96: { key: 'MISSING_TSV_COLUMN_EEG_ELECTRODES', severity: 'error', reason: "The column names of the electrodes file must begin with ['name', 'x', 'y', 'z']", }, 97: { key: 'MISSING_SESSION', severity: 'warning', reason: 'Not all subjects contain the same sessions.' } }
utils/issues/list.js
/** * Issues * * A list of all possible issues organized by * issue code and including severity and reason * agnostic to file specifics. */ module.exports = { 0: { key: 'INTERNAL ERROR', severity: 'error', reason: 'Internal error. SOME VALIDATION STEPS MAY NOT HAVE OCCURRED', }, 1: { key: 'NOT_INCLUDED', severity: 'error', reason: 'Files with such naming scheme are not part of BIDS specification. This error is most commonly ' + 'caused by typos in file names that make them not BIDS compatible. Please consult the specification and ' + 'make sure your files are named correctly. If this is not a file naming issue (for example when including ' + 'files not yet covered by the BIDS specification) you should include a ".bidsignore" file in your dataset (see' + ' https://github.com/bids-standard/bids-validator#bidsignore for details). Please ' + 'note that derived (processed) data should be placed in /derivatives folder and source data (such as DICOMS ' + 'or behavioural logs in proprietary formats) should be placed in the /sourcedata folder.', }, 2: { key: 'REPETITION_TIME_GREATER_THAN', severity: 'warning', reason: "'RepetitionTime' is greater than 100 are you sure it's expressed in seconds?", }, 3: { key: 'ECHO_TIME_GREATER_THAN', severity: 'warning', reason: "'EchoTime' is greater than 1 are you sure it's expressed in seconds?", }, 4: { key: 'ECHO_TIME_DIFFERENCE_GREATER_THAN', severity: 'warning', reason: "'EchoTimeDifference' is greater than 1 are you sure it's expressed in seconds?", }, 5: { key: 'TOTAL_READOUT_TIME_GREATER_THAN', severity: 'warning', reason: "'TotalReadoutTime' is greater than 10 are you sure it's expressed in seconds?", }, 6: { key: 'ECHO_TIME_NOT_DEFINED', severity: 'warning', reason: "You should define 'EchoTime' for this file. If you don't provide this information field map correction will not be possible.", }, 7: { key: 'PHASE_ENCODING_DIRECTION_NOT_DEFINED', severity: 'warning', reason: "You should define 'PhaseEncodingDirection' for this file. If you don't provide this information field map correction will not be possible.", }, 8: { key: 'EFFECTIVE_ECHO_SPACING_NOT_DEFINED', severity: 'warning', reason: "You should define 'EffectiveEchoSpacing' for this file. If you don't provide this information field map correction will not be possible.", }, 9: { key: 'TOTAL_READOUT_TIME_NOT_DEFINED', severity: 'warning', reason: "You should define 'TotalReadoutTime' for this file. If you don't provide this information field map correction using TOPUP might not be possible.", }, 10: { key: 'REPETITION_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'RepetitionTime' for this file.", }, 11: { key: 'REPETITION_TIME_UNITS', severity: 'error', reason: "Repetition time was not defined in seconds, milliseconds or microseconds in the scan's header.", }, 12: { key: 'REPETITION_TIME_MISMATCH', severity: 'error', reason: "Repetition time did not match between the scan's header and the associated JSON metadata file.", }, 13: { key: 'SLICE_TIMING_NOT_DEFINED', severity: 'warning', reason: "You should define 'SliceTiming' for this file. If you don't provide this information slice time correction will not be possible.", }, 15: { key: 'ECHO_TIME1-2_NOT_DEFINED', severity: 'error', reason: "You have to define 'EchoTime1' and 'EchoTime2' for this file.", }, 16: { key: 'ECHO_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'EchoTime' for this file.", }, 17: { key: 'UNITS_MUST_DEFINE', severity: 'error', reason: "You have to define 'Units' for this file.", }, 18: { key: 'PHASE_ENCODING_DIRECTION_MUST_DEFINE', severity: 'error', reason: "You have to define 'PhaseEncodingDirection' for this file.", }, 19: { key: 'TOTAL_READOUT_TIME_MUST_DEFINE', severity: 'error', reason: "You have to define 'TotalReadoutTime' for this file.", }, 20: { key: 'EVENTS_COLUMN_ONSET', severity: 'error', reason: "First column of the events file must be named 'onset'", }, 21: { key: 'EVENTS_COLUMN_DURATION', severity: 'error', reason: "Second column of the events file must be named 'duration'", }, 22: { key: 'TSV_EQUAL_ROWS', severity: 'error', reason: 'All rows must have the same number of columns as there are headers.', }, 23: { key: 'TSV_EMPTY_CELL', severity: 'error', reason: 'Empty cell in TSV file detected: The proper way of labeling missing values is "n/a".', }, 24: { key: 'TSV_IMPROPER_NA', severity: 'warning', reason: 'A proper way of labeling missing values is "n/a".', }, 25: { key: 'EVENTS_TSV_MISSING', severity: 'warning', reason: 'Task scans should have a corresponding events.tsv file. If this is a resting state scan you can ignore this warning or rename the task to include the word "rest".', }, 26: { key: 'NIFTI_HEADER_UNREADABLE', severity: 'error', reason: 'We were unable to parse header data from this NIfTI file. Please ensure it is not corrupted or mislabeled.', }, 27: { key: 'JSON_INVALID', severity: 'error', reason: 'Not a valid JSON file.', }, 28: { key: 'GZ_NOT_GZIPPED', severity: 'error', reason: 'This file ends in the .gz extension but is not actually gzipped.', }, 29: { key: 'VOLUME_COUNT_MISMATCH', severity: 'error', reason: 'The number of volumes in this scan does not match the number of volumes in the corresponding .bvec and .bval files.', }, 30: { key: 'BVAL_MULTIPLE_ROWS', severity: 'error', reason: '.bval files should contain exactly one row of volumes.', }, 31: { key: 'BVEC_NUMBER_ROWS', severity: 'error', reason: '.bvec files should contain exactly three rows of volumes.', }, 32: { key: 'DWI_MISSING_BVEC', severity: 'error', reason: 'DWI scans should have a corresponding .bvec file.', }, 33: { key: 'DWI_MISSING_BVAL', severity: 'error', reason: 'DWI scans should have a corresponding .bval file.', }, 36: { key: 'NIFTI_TOO_SMALL', severity: 'error', reason: 'This file is too small to contain the minimal NIfTI header.', }, 37: { key: 'INTENDED_FOR', severity: 'error', reason: "'IntendedFor' field needs to point to an existing file.", }, 38: { key: 'INCONSISTENT_SUBJECTS', severity: 'warning', reason: 'Not all subjects contain the same files. Each subject should contain the same number of files with ' + 'the same naming unless some files are known to be missing.', }, 39: { key: 'INCONSISTENT_PARAMETERS', severity: 'warning', reason: 'Not all subjects/sessions/runs have the same scanning parameters.', }, 40: { key: 'NIFTI_DIMENSION', severity: 'warning', reason: "Nifti file's header field for dimension information blank or too short.", }, 41: { key: 'NIFTI_UNIT', severity: 'warning', reason: "Nifti file's header field for unit information for x, y, z, and t dimensions empty or too short", }, 42: { key: 'NIFTI_PIXDIM', severity: 'warning', reason: "Nifti file's header field for pixel dimension information empty or too short.", }, 43: { key: 'ORPHANED_SYMLINK', severity: 'error', reason: 'This file appears to be an orphaned symlink. Make sure it correctly points to its referent.', }, 44: { key: 'FILE_READ', severity: 'error', reason: 'We were unable to read this file. Make sure it is not corrupted, incorrectly named or incorrectly symlinked.', }, 45: { key: 'SUBJECT_FOLDERS', severity: 'error', reason: 'There are no subject folders (labeled "sub-*") in the root of this dataset.', }, 46: { key: 'BVEC_ROW_LENGTH', severity: 'error', reason: 'Each row in a .bvec file should contain the same number of values.', }, 47: { key: 'B_FILE', severity: 'error', reason: '.bval and .bvec files must be single space delimited and contain only numerical values.', }, 48: { key: 'PARTICIPANT_ID_COLUMN', severity: 'error', reason: "Participants and phenotype .tsv files must have a 'participant_id' column.", }, 49: { key: 'PARTICIPANT_ID_MISMATCH', severity: 'error', reason: 'Participant labels found in this dataset did not match the values in participant_id column found in the participants.tsv file.', }, 50: { key: 'TASK_NAME_MUST_DEFINE', severity: 'error', reason: "You have to define 'TaskName' for this file.", }, 51: { key: 'PHENOTYPE_SUBJECTS_MISSING', severity: 'error', reason: 'A phenotype/ .tsv file lists subjects that were not found in the dataset.', }, 52: { key: 'STIMULUS_FILE_MISSING', severity: 'error', reason: 'A stimulus file was declared but not found in the dataset.', }, 53: { key: 'NO_T1W', severity: 'ignore', reason: 'Dataset does not contain any T1w scans.', }, 54: { key: 'BOLD_NOT_4D', severity: 'error', reason: 'Bold scans must be 4 dimensional.', }, 55: { key: 'JSON_SCHEMA_VALIDATION_ERROR', severity: 'error', reason: 'Invalid JSON file. The file is not formatted according the schema.', }, 56: { key: 'Participants age 89 or higher', severity: 'warning', reason: 'As per section 164.514(C) of "The De-identification Standard" under HIPAA guidelines, participants with age 89 or higher should be tagged as 89+. More information can be found at https://www.hhs.gov/hipaa/for-professionals/privacy/special-topics/de-identification/#standard', }, 57: { key: 'DATASET_DESCRIPTION_JSON_MISSING', severity: 'error', reason: 'The compulsory file /dataset_description.json is missing. See Section 8.1 of the BIDS specification.', }, 58: { key: 'TASK_NAME_CONTAIN_ILLEGAL_CHARACTER', severity: 'error', reason: 'Task Name contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 59: { key: 'ACQ_NAME_CONTAIN_ILLEGAL_CHARACTER', severity: 'error', reason: 'acq Name contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 60: { key: 'SFORM_AND_QFORM_IN_IMAGE_HEADER_ARE_ZERO', severity: 'error', reason: 'sform_code and qform_code in the image header are 0. The image/file will be considered invalid or assumed to be in LAS orientation.', }, 61: { key: 'QUICK_VALIDATION_FAILED', severity: 'error', reason: 'Quick validation failed - the general folder structure does not resemble a BIDS dataset. Have you chosen the right folder (with "sub-*/" subfolders)? Check for structural/naming issues and presence of at least one subject.', }, 62: { key: 'SUBJECT_VALUE_CONTAINS_ILLEGAL_CHARECTER', severity: 'error', reason: 'Sub label contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 63: { key: 'SESSION_VALUE_CONTAINS_ILLEGAL_CHARECTER', severity: 'error', reason: 'Ses label contain an Illegal Character hyphen or underscore. Please edit the filename as per BIDS spec.', }, 64: { key: 'SUBJECT_LABEL_IN_FILENAME_DOESNOT_MATCH_DIRECTORY', severity: 'error', reason: "Subject label in the filename doesn't match with the path of the file. File seems to be saved in incorrect subject directory.", }, 65: { key: 'SESSION_LABEL_IN_FILENAME_DOESNOT_MATCH_DIRECTORY', severity: 'error', reason: "Session label in the filename doesn't match with the path of the file. File seems to be saved in incorrect session directory.", }, 66: { key: 'SLICETIMING_VALUES_GREATOR_THAN_REPETITION_TIME', severity: 'error', reason: '"SliceTiming" value/s contains invalid value as it is greater than RepetitionTime. SliceTiming values should be in seconds not milliseconds (common mistake).', }, 67: { key: 'NO_VALID_DATA_FOUND_FOR_SUBJECT', severity: 'error', reason: 'No BIDS compatible data found for at least one subject.', }, 68: { key: 'FILENAME_COLUMN', severity: 'error', reason: "_scans.tsv files must have a 'filename' column.", }, 70: { key: 'WRONG_NEW_LINE', severity: 'error', reason: "All TSV files must use Line Feed '\\n' characters to denote new lines. This files uses Carriage Return '\\r'.", }, 71: { key: 'MISSING_TSV_COLUMN_CHANNELS', severity: 'error', reason: "The column names of the channels file must begin with ['name', 'type', 'units']", }, 72: { key: 'MISSING_TSV_COLUMN_IEEG_CHANNELS', severity: 'error', reason: "The column names of the channels file must begin with ['name', 'type', 'units', 'sampling_frequency', 'low_cutoff', 'high_cutoff', 'notch', 'reference']", }, 73: { key: 'MISSING_TSV_COLUMN_IEEG_ELECTRODES', severity: 'error', reason: "The column names of the electrodes file must begin with ['name', 'x', 'y', 'z', 'size', 'type']", }, 74: { key: 'DUPLICATE_NIFTI_FILES', severity: 'error', reason: "Nifti file exist with both '.nii' and '.nii.gz' extensions.", }, 75: { key: 'NIFTI_PIXDIM4', severity: 'error', reason: "Nifti file's header is missing time dimension information.", }, 76: { key: 'EFFECTIVEECHOSPACING_TOO_LARGE', severity: 'error', reason: "Abnormally high value of 'EffectiveEchoSpacing'.", }, 77: { key: 'UNUSED_STIMULUS', severity: 'warning', reason: 'There are files in the /stimuli directory that are not utilized in any _events.tsv file.', }, 78: { key: 'CHANNELS_COLUMN_SFREQ', severity: 'error', reason: "Fourth column of the channels file must be named 'sampling_frequency'", }, 79: { key: 'CHANNELS_COLUMN_LOWCUT', severity: 'error', reason: "Third column of the channels file must be named 'low_cutoff'", }, 80: { key: 'CHANNELS_COLUMN_HIGHCUT', severity: 'error', reason: "Third column of the channels file must be named 'high_cutoff'", }, 81: { key: 'CHANNELS_COLUMN_NOTCH', severity: 'error', reason: "Third column of the channels file must be named 'notch'", }, 82: { key: 'CUSTOM_COLUMN_WITHOUT_DESCRIPTION', severity: 'warning', reason: 'Tabular file contains custom columns not described in a data dictionary', }, 83: { key: 'ECHOTIME1_2_DIFFERENCE_UNREASONABLE', severity: 'error', reason: 'The value of (EchoTime2 - EchoTime1) should be within the range of 0.0001 - 0.01.', }, 84: { key: 'ACQTIME_FMT', severity: 'error', reason: 'Entries in the "acq_time" column of _scans.tsv should be expressed in the following format YYYY-MM-DDTHH:mm:ss (year, month, day, hour (24h), minute, second; this is equivalent to the RFC3339 “date-time” format. ', }, 85: { key: 'SUSPICIOUSLY_LONG_EVENT_DESIGN', severity: 'warning', reason: 'The onset of the last event is after the total duration of the corresponding scan. This design is suspiciously long. ', }, 86: { key: 'SUSPICIOUSLY_SHORT_EVENT_DESIGN', severity: 'warning', reason: 'The onset of the last event is less than half the total duration of the corresponding scan. This design is suspiciously short. ', }, 87: { key: 'SLICETIMING_ELEMENTS', severity: 'warning', reason: "The number of elements in the SliceTiming array should match the 'k' dimension of the corresponding nifti volume.", }, 88: { key: 'MALFORMED_BVEC', severity: 'error', reason: 'The contents of this .bvec file are undefined or severely malformed. ', }, 89: { key: 'MALFORMED_BVAL', severity: 'error', reason: 'The contents of this .bval file are undefined or severely malformed. ', }, 90: { key: 'SIDECAR_WITHOUT_DATAFILE', severity: 'error', reason: 'A json sidecar file was found without a corresponding data file', }, 91: { key: '_FIELDMAP_WITHOUT_MAGNITUDE_FILE', severity: 'error', reason: '_fieldmap.nii[.gz] file does not have accompanying _magnitude.nii[.gz] file. ', }, 92: { key: 'MISSING_MAGNITUDE1_FILE', severity: 'warning', reason: 'Each _phasediff.nii[.gz] file should be associated with a _magnitude1.nii[.gz] file.', }, 93: { key: 'EFFECTIVEECHOSPACING_LARGER_THAN_TOTALREADOUTTIME', severity: 'error', reason: 'EffectiveEchoSpacing should always be smaller than TotalReadoutTime. ', }, 94: { key: 'MAGNITUDE_FILE_WITH_TOO_MANY_DIMENSIONS', severity: 'error', reason: '_magnitude1.nii[.gz] and _magnitude2.nii[.gz] files must have exactly three dimensions. ', }, 95: { key: 'T1W_FILE_WITH_TOO_MANY_DIMENSIONS', severity: 'error', reason: '_T1w.nii[.gz] files must have exactly three dimensions. ', }, 96: { key: 'MISSING_TSV_COLUMN_EEG_ELECTRODES', severity: 'error', reason: "The column names of the electrodes file must begin with ['name', 'x', 'y', 'z']", }, }
add MISSING_SECTION warning to issue list
utils/issues/list.js
add MISSING_SECTION warning to issue list
<ide><path>tils/issues/list.js <ide> reason: <ide> "The column names of the electrodes file must begin with ['name', 'x', 'y', 'z']", <ide> }, <add> 97: { <add> key: 'MISSING_SESSION', <add> severity: 'warning', <add> reason: 'Not all subjects contain the same sessions.' <add> } <ide> }
Java
apache-2.0
43652575d047f23b13f7d06648d68dfa211ae3ac
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.core.jdbc.core.datasource; import io.shardingsphere.core.api.ConfigMapContext; import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration; import io.shardingsphere.core.constant.properties.ShardingProperties; import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import io.shardingsphere.core.jdbc.adapter.AbstractDataSourceAdapter; import io.shardingsphere.core.jdbc.core.connection.MasterSlaveConnection; import io.shardingsphere.core.rule.MasterSlaveRule; import lombok.Getter; import javax.sql.DataSource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Properties; /** * Database that support master-slave. * * @author zhangliang */ @Getter public class MasterSlaveDataSource extends AbstractDataSourceAdapter implements AutoCloseable { private Map<String, DataSource> dataSourceMap; private MasterSlaveRule masterSlaveRule; private ShardingProperties shardingProperties; public MasterSlaveDataSource(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final Map<String, Object> configMap, final Properties props) throws SQLException { super(getAllDataSources(dataSourceMap, masterSlaveRuleConfig.getMasterDataSourceName(), masterSlaveRuleConfig.getSlaveDataSourceNames())); this.dataSourceMap = dataSourceMap; this.masterSlaveRule = new MasterSlaveRule(masterSlaveRuleConfig); if (!configMap.isEmpty()) { ConfigMapContext.getInstance().getMasterSlaveConfig().putAll(configMap); } shardingProperties = new ShardingProperties(null == props ? new Properties() : props); } private static Collection<DataSource> getAllDataSources(final Map<String, DataSource> dataSourceMap, final String masterDataSourceName, final Collection<String> slaveDataSourceNames) { Collection<DataSource> result = new LinkedList<>(); result.add(dataSourceMap.get(masterDataSourceName)); for (String each : slaveDataSourceNames) { result.add(dataSourceMap.get(each)); } return result; } /** * Get map of all actual data source name and all actual data sources. * * @return map of all actual data source name and all actual data sources */ public Map<String, DataSource> getAllDataSources() { Map<String, DataSource> result = new HashMap<>(masterSlaveRule.getSlaveDataSourceNames().size() + 1, 1); result.put(masterSlaveRule.getMasterDataSourceName(), dataSourceMap.get(masterSlaveRule.getMasterDataSourceName())); for (String each : masterSlaveRule.getSlaveDataSourceNames()) { result.put(each, dataSourceMap.get(each)); } return result; } /** * Renew master-slave data source. * * @param dataSourceMap data source map * @param masterSlaveRuleConfig new master-slave rule configuration */ public void renew(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig) { closeOriginalDataSources(); this.dataSourceMap = dataSourceMap; this.masterSlaveRule = new MasterSlaveRule(masterSlaveRuleConfig); } private void closeOriginalDataSources() { for (DataSource each : this.dataSourceMap.values()) { try { System.err.println("ms begin close datasource"); Method closeMethod = each.getClass().getDeclaredMethod("close"); Method shutDownMethod = each.getClass().getDeclaredMethod("shutdown"); closeMethod.invoke(each); shutDownMethod.invoke(each); System.err.println("ms finish close datasource"); } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { } } } @Override public final MasterSlaveConnection getConnection() { return new MasterSlaveConnection(this); } @Override public void close() { closeOriginalDataSources(); } /** * Show SQL or not. * * @return show SQL or not */ public boolean showSQL() { return shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW); } }
sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/datasource/MasterSlaveDataSource.java
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.core.jdbc.core.datasource; import io.shardingsphere.core.api.ConfigMapContext; import io.shardingsphere.core.api.config.MasterSlaveRuleConfiguration; import io.shardingsphere.core.constant.properties.ShardingProperties; import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import io.shardingsphere.core.jdbc.adapter.AbstractDataSourceAdapter; import io.shardingsphere.core.jdbc.core.connection.MasterSlaveConnection; import io.shardingsphere.core.rule.MasterSlaveRule; import lombok.Getter; import javax.sql.DataSource; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Properties; /** * Database that support master-slave. * * @author zhangliang */ @Getter public class MasterSlaveDataSource extends AbstractDataSourceAdapter implements AutoCloseable { private Map<String, DataSource> dataSourceMap; private MasterSlaveRule masterSlaveRule; private ShardingProperties shardingProperties; public MasterSlaveDataSource(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig, final Map<String, Object> configMap, final Properties props) throws SQLException { super(getAllDataSources(dataSourceMap, masterSlaveRuleConfig.getMasterDataSourceName(), masterSlaveRuleConfig.getSlaveDataSourceNames())); this.dataSourceMap = dataSourceMap; this.masterSlaveRule = new MasterSlaveRule(masterSlaveRuleConfig); if (!configMap.isEmpty()) { ConfigMapContext.getInstance().getMasterSlaveConfig().putAll(configMap); } shardingProperties = new ShardingProperties(null == props ? new Properties() : props); } private static Collection<DataSource> getAllDataSources(final Map<String, DataSource> dataSourceMap, final String masterDataSourceName, final Collection<String> slaveDataSourceNames) { Collection<DataSource> result = new LinkedList<>(); result.add(dataSourceMap.get(masterDataSourceName)); for (String each : slaveDataSourceNames) { result.add(dataSourceMap.get(each)); } return result; } /** * Get map of all actual data source name and all actual data sources. * * @return map of all actual data source name and all actual data sources */ public Map<String, DataSource> getAllDataSources() { Map<String, DataSource> result = new HashMap<>(masterSlaveRule.getSlaveDataSourceNames().size() + 1, 1); result.put(masterSlaveRule.getMasterDataSourceName(), dataSourceMap.get(masterSlaveRule.getMasterDataSourceName())); for (String each : masterSlaveRule.getSlaveDataSourceNames()) { result.put(each, dataSourceMap.get(each)); } return result; } /** * Renew master-slave data source. * * @param dataSourceMap data source map * @param masterSlaveRuleConfig new master-slave rule configuration */ public void renew(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig) { this.dataSourceMap = dataSourceMap; this.masterSlaveRule = new MasterSlaveRule(masterSlaveRuleConfig); } private void closeOriginalDataSources() { for (DataSource each : this.dataSourceMap.values()) { try { System.err.println("ms begin close datasource"); Method closeMethod = each.getClass().getDeclaredMethod("close"); Method shutDownMethod = each.getClass().getDeclaredMethod("shutdown"); closeMethod.invoke(each); shutDownMethod.invoke(each); System.err.println("ms finish close datasource"); } catch (final NoSuchMethodException | InvocationTargetException | IllegalAccessException ignored) { } } } @Override public final MasterSlaveConnection getConnection() { return new MasterSlaveConnection(this); } @Override public void close() { closeOriginalDataSources(); } /** * Show SQL or not. * * @return show SQL or not */ public boolean showSQL() { return shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW); } }
use closeOriginalDataSources()
sharding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/datasource/MasterSlaveDataSource.java
use closeOriginalDataSources()
<ide><path>harding-jdbc/src/main/java/io/shardingsphere/core/jdbc/core/datasource/MasterSlaveDataSource.java <ide> * @param masterSlaveRuleConfig new master-slave rule configuration <ide> */ <ide> public void renew(final Map<String, DataSource> dataSourceMap, final MasterSlaveRuleConfiguration masterSlaveRuleConfig) { <add> closeOriginalDataSources(); <ide> this.dataSourceMap = dataSourceMap; <ide> this.masterSlaveRule = new MasterSlaveRule(masterSlaveRuleConfig); <ide> }
Java
apache-2.0
error: pathspec 'algorithm/src/test/java/org/wuxinshui/boosters/algerithom/sort/InsertionSortTest.java' did not match any file(s) known to git
ae74eb047731589c1198091cb0a5b2091a49aa45
1
wuxinshui/boosters
package org.wuxinshui.boosters.algerithom.sort; import org.junit.Test; import java.util.Arrays; import static org.wuxinshui.boosters.algerithom.sort.InsertionSort.dichotomyInsertionSort; import static org.wuxinshui.boosters.algerithom.sort.InsertionSort.simpleInsertionSort01; /** * Created by FujiRen on 2016/9/6. * 插入排序单元测试 */ public class InsertionSortTest { @Test public void test01() { int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; } /** * 直接插入排序单元测试 */ @Test public void testSimpleInsertionSort01() { int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; System.out.println("直接插入排序,排序前:" + Arrays.toString(a)); simpleInsertionSort01(a); System.out.println("直接插入排序,排序后:" + Arrays.toString(a)); } /** * 直接插入排序单元测试 */ @Test public void testDichotomyInsertionSort() { int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; System.out.println("直接插入排序,排序前:" + Arrays.toString(a)); dichotomyInsertionSort(a); System.out.println("直接插入排序,排序后:" + Arrays.toString(a)); } }
algorithm/src/test/java/org/wuxinshui/boosters/algerithom/sort/InsertionSortTest.java
插入排序测试
algorithm/src/test/java/org/wuxinshui/boosters/algerithom/sort/InsertionSortTest.java
插入排序测试
<ide><path>lgorithm/src/test/java/org/wuxinshui/boosters/algerithom/sort/InsertionSortTest.java <add>package org.wuxinshui.boosters.algerithom.sort; <add> <add>import org.junit.Test; <add> <add>import java.util.Arrays; <add> <add>import static org.wuxinshui.boosters.algerithom.sort.InsertionSort.dichotomyInsertionSort; <add>import static org.wuxinshui.boosters.algerithom.sort.InsertionSort.simpleInsertionSort01; <add> <add>/** <add> * Created by FujiRen on 2016/9/6. <add> * 插入排序单元测试 <add> */ <add>public class InsertionSortTest { <add> @Test <add> public void test01() { <add> int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; <add> } <add> <add> /** <add> * 直接插入排序单元测试 <add> */ <add> @Test <add> public void testSimpleInsertionSort01() { <add> int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; <add> System.out.println("直接插入排序,排序前:" + Arrays.toString(a)); <add> simpleInsertionSort01(a); <add> System.out.println("直接插入排序,排序后:" + Arrays.toString(a)); <add> } <add> /** <add> * 直接插入排序单元测试 <add> */ <add> @Test <add> public void testDichotomyInsertionSort() { <add> int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1}; <add> System.out.println("直接插入排序,排序前:" + Arrays.toString(a)); <add> dichotomyInsertionSort(a); <add> System.out.println("直接插入排序,排序后:" + Arrays.toString(a)); <add> } <add> <add> <add> <add>}
JavaScript
mit
a34bd6dd31618ef4fb4c40ec1623d68b563c0a46
0
jxson/haiku
lib/haiku/content.js
// var // , mkdirp = require('mkdirp') // ; var Origami = require('haiku/origami') , fs = require('fs') , yaml = require('yamlparser') , path = require('path') , _ = require('underscore') , Mustache = require('mustache') , markdown = require('marked') , textile = require('stextile') , colors = require('colors') ; var Content = Origami.extend({ initialize: function(attributes, haiku){ if (haiku) this.haiku = haiku; }, toView: function(helpers){ var content = this , view = _.clone(this.attributes) , helpers = helpers || {} , defaultHelpers ; defaultHelpers = { url: content.url(), related: content.related(), content: function(){ var view = content.toView({ site: content.haiku.toView() }) , partials = content.haiku.partials ; try { return Mustache.to_html(c._template, view, partials); } catch(err) { var newErr = new Error([ 'MUSTACHE ERROR :{', ' ' + content.get('file'), '', ' Template:', content._template ].join('\n')); throw newErr; } } }; _.extend(view, defaultHelpers, helpers); return view; }, defaults: { layout: 'default', publish: true }, read: function(){ var content = this; this.extractAttributesFromFile(function(err){ if (err) throw err; content.emit('ready'); }); }, extractAttributesFromFile: function(callback){ // http://stackoverflow.com/q/1068308 var regex = /^(\s*---([\s\S]+)---\s*)/gi , content = this , file = this.get('file') ; fs.readFile(file, 'utf8', function(err, data){ if (err) throw err; var match = regex.exec(data); if (match && match.length > 0){ var yamlString = match[2].replace(/^\s+|\s+$/g, '') , template = data.replace(match[0], '') , yamlAttributes ; attributes = yaml.eval(yamlString); content._template = content.parse(template); content.set(attributes); callback(); } else { content._template = content.parse(data); callback(); } }); }, parser: function(){ if (!this.get('file')) return; var extname = path.extname(this.get('file')) , markdownExtensions = ['.md', '.markdown', '.mdown', '.mkdn', '.mkd'] , htmlExtensions = ['.mustache', '.html'] ; if (_.include(markdownExtensions, extname)){ return 'markdown'; } if (extname === '.textile'){ return 'textile'; } if (_.include(htmlExtensions, extname)){ return undefined; } }, parse: function(content){ var parser = this.parser(); if (parser === 'markdown') return markdown(content); if (parser === 'textile') return textile(content) return content; }, url: function(){ if (! this.get('file')) return; // TODO: this should allow a configurable prefix return '/' + this.buildpath(); }, buildpath: function(){ if (! this.get('file')) return; var pathname = this.get('file').replace(/(.*)\/content\//g, '') basename = path.basename(pathname) dots = _.without(basename.split('.'), 'mustache') extension = 'html' ; // No extension? defaults to .html if (dots.length === 1) dots.push(extension); newBasename = dots.join('.'); return pathname.replace(basename, newBasename); }, // this should become async render: function(callback){ var layouts = this.haiku.layouts , content = this , partials = content.haiku.partials , layout = layouts[content.get('layout')] , template = content._template , html , err ; var view = content.toView({ site: content.haiku.toView(), yield: function(){ var contentView = content.toView({ site: content.haiku.toView() }); return Mustache.to_html(template, contentView, partials); } }); if (!layout){ var message = [ 'Missing layout: "', content.get('layout'), '"' ].join(''); throw new Error(message); } try { html = Mustache.to_html(layout, view, partials); } catch (e) { err = e; } callback(err, html); }, isInCollection: function(){ this._getCollectionFromFile(); if (this.get('collection')) return true; else return false; }, collection: function(){ return this._getCollectionFromFile(); }, _getCollectionFromFile: function(){ var file = this.get('file') , contentdir = this.haiku.contentdir() , relativepath = file.replace(contentdir, '') , basename = path.basename(file) , directories = relativepath.split('/') , collection = '' ; _(directories) .chain() .compact() .without(basename) .each(function(dir){ if (collection.length === 0) collection += dir else collection += ('_' + dir) }); if (collection.length === 0) return; this.set({ collection: collection }); return collection; }, related: function(){ var content = this , collection = this.collection() , contentInCollection = _.clone(this.haiku.get(collection)) , related ; related = _(contentInCollection) .chain() .map(function(value, key){ var intersection = _.intersection(content.get('tags'), value.tags); if (intersection.length > 0 && content.url() !== value.url){ return value; } }).compact().value().slice(0, 10); return related; } }); exports = module.exports = Content;
remove the old content.js
lib/haiku/content.js
remove the old content.js
<ide><path>ib/haiku/content.js <del>// var <del>// , mkdirp = require('mkdirp') <del>// ; <del> <del>var Origami = require('haiku/origami') <del> , fs = require('fs') <del> , yaml = require('yamlparser') <del> , path = require('path') <del> , _ = require('underscore') <del> , Mustache = require('mustache') <del> , markdown = require('marked') <del> , textile = require('stextile') <del> <del> , colors = require('colors') <del>; <del> <del>var Content = Origami.extend({ <del> initialize: function(attributes, haiku){ <del> if (haiku) this.haiku = haiku; <del> }, <del> <del> toView: function(helpers){ <del> var content = this <del> , view = _.clone(this.attributes) <del> , helpers = helpers || {} <del> , defaultHelpers <del> ; <del> <del> defaultHelpers = { <del> url: content.url(), <del> related: content.related(), <del> content: function(){ <del> var view = content.toView({ <del> site: content.haiku.toView() <del> }) <del> , partials = content.haiku.partials <del> ; <del> <del> try { <del> return Mustache.to_html(c._template, view, partials); <del> } catch(err) { <del> var newErr = new Error([ <del> 'MUSTACHE ERROR :{', <del> ' ' + content.get('file'), <del> '', <del> ' Template:', <del> content._template <del> ].join('\n')); <del> throw newErr; <del> } <del> <del> } <del> }; <del> <del> _.extend(view, defaultHelpers, helpers); <del> <del> return view; <del> }, <del> <del> defaults: { <del> layout: 'default', <del> publish: true <del> }, <del> <del> read: function(){ <del> var content = this; <del> <del> this.extractAttributesFromFile(function(err){ <del> if (err) throw err; <del> <del> content.emit('ready'); <del> }); <del> }, <del> <del> extractAttributesFromFile: function(callback){ <del> // http://stackoverflow.com/q/1068308 <del> var regex = /^(\s*---([\s\S]+)---\s*)/gi <del> , content = this <del> , file = this.get('file') <del> ; <del> <del> fs.readFile(file, 'utf8', function(err, data){ <del> if (err) throw err; <del> <del> var match = regex.exec(data); <del> <del> if (match && match.length > 0){ <del> var yamlString = match[2].replace(/^\s+|\s+$/g, '') <del> , template = data.replace(match[0], '') <del> , yamlAttributes <del> ; <del> <del> attributes = yaml.eval(yamlString); <del> <del> content._template = content.parse(template); <del> <del> content.set(attributes); <del> <del> callback(); <del> } else { <del> content._template = content.parse(data); <del> callback(); <del> } <del> }); <del> }, <del> <del> parser: function(){ <del> if (!this.get('file')) return; <del> <del> var extname = path.extname(this.get('file')) <del> , markdownExtensions = ['.md', '.markdown', '.mdown', '.mkdn', '.mkd'] <del> , htmlExtensions = ['.mustache', '.html'] <del> ; <del> <del> if (_.include(markdownExtensions, extname)){ <del> return 'markdown'; <del> } <del> <del> if (extname === '.textile'){ <del> return 'textile'; <del> } <del> <del> if (_.include(htmlExtensions, extname)){ <del> return undefined; <del> } <del> }, <del> <del> parse: function(content){ <del> var parser = this.parser(); <del> <del> if (parser === 'markdown') return markdown(content); <del> if (parser === 'textile') return textile(content) <del> <del> return content; <del> }, <del> <del> url: function(){ <del> if (! this.get('file')) return; <del> <del> // TODO: this should allow a configurable prefix <del> return '/' + this.buildpath(); <del> }, <del> <del> buildpath: function(){ <del> if (! this.get('file')) return; <del> <del> var pathname = this.get('file').replace(/(.*)\/content\//g, '') <del> basename = path.basename(pathname) <del> dots = _.without(basename.split('.'), 'mustache') <del> extension = 'html' <del> ; <del> <del> // No extension? defaults to .html <del> if (dots.length === 1) dots.push(extension); <del> <del> newBasename = dots.join('.'); <del> <del> return pathname.replace(basename, newBasename); <del> }, <del> <del> // this should become async <del> render: function(callback){ <del> var layouts = this.haiku.layouts <del> , content = this <del> , partials = content.haiku.partials <del> , layout = layouts[content.get('layout')] <del> , template = content._template <del> , html <del> , err <del> ; <del> <del> var view = content.toView({ <del> site: content.haiku.toView(), <del> yield: function(){ <del> var contentView = content.toView({ <del> site: content.haiku.toView() <del> }); <del> <del> return Mustache.to_html(template, contentView, partials); <del> } <del> }); <del> <del> if (!layout){ <del> var message = [ <del> 'Missing layout: "', <del> content.get('layout'), <del> '"' <del> ].join(''); <del> <del> throw new Error(message); <del> } <del> <del> try { <del> html = Mustache.to_html(layout, view, partials); <del> } catch (e) { <del> err = e; <del> } <del> <del> callback(err, html); <del> }, <del> <del> isInCollection: function(){ <del> this._getCollectionFromFile(); <del> <del> if (this.get('collection')) return true; <del> else return false; <del> }, <del> <del> collection: function(){ <del> return this._getCollectionFromFile(); <del> }, <del> <del> _getCollectionFromFile: function(){ <del> var file = this.get('file') <del> , contentdir = this.haiku.contentdir() <del> , relativepath = file.replace(contentdir, '') <del> , basename = path.basename(file) <del> , directories = relativepath.split('/') <del> , collection = '' <del> ; <del> <del> _(directories) <del> .chain() <del> .compact() <del> .without(basename) <del> .each(function(dir){ <del> if (collection.length === 0) collection += dir <del> else collection += ('_' + dir) <del> }); <del> <del> if (collection.length === 0) return; <del> <del> this.set({ collection: collection }); <del> <del> return collection; <del> }, <del> <del> related: function(){ <del> var content = this <del> , collection = this.collection() <del> , contentInCollection = _.clone(this.haiku.get(collection)) <del> , related <del> ; <del> <del> related = _(contentInCollection) <del> .chain() <del> .map(function(value, key){ <del> var intersection = _.intersection(content.get('tags'), value.tags); <del> <del> if (intersection.length > 0 && content.url() !== value.url){ <del> return value; <del> } <del> }).compact().value().slice(0, 10); <del> <del> return related; <del> } <del>}); <del> <del>exports = module.exports = Content;
Java
apache-2.0
9da4e746e57134d1eb43b9f00cae4a65e226bc9b
0
arrow-acs/acn-sdk-java
/******************************************************************************* * Copyright (c) 2017 Arrow Electronics, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License 2.0 * which accompanies this distribution, and is available at * http://apache.org/licenses/LICENSE-2.0 * * Contributors: * Arrow Electronics, Inc. *******************************************************************************/ package com.arrow.acn.client.api; import java.net.URI; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import com.arrow.acn.client.AcnClientException; import com.arrow.acn.client.model.DeviceActionModel; import com.arrow.acn.client.model.DeviceActionTypeModel; import com.arrow.acs.JsonUtils; import com.arrow.acs.client.api.ApiConfig; import com.arrow.acs.client.model.HidModel; import com.arrow.acs.client.model.ListResultModel; import com.fasterxml.jackson.core.type.TypeReference; public class DeviceActionApi extends ApiAbstract { private static final String DEVICES_BASE_URL = API_BASE + "/devices"; private static final String ACTION_TYPES_URL = DEVICES_BASE_URL + "/actions/types"; private static final String SPECIFIC_DEVICE_URL = DEVICES_BASE_URL + "/{hid}"; private static final String SPECIFIC_DEVICE_ACTIONS_URL = SPECIFIC_DEVICE_URL + "/actions"; private static final String SPECIFIC_ACTION_URL = SPECIFIC_DEVICE_ACTIONS_URL + "/{index}"; private static final String DEVICE_TYPES_URL = DEVICES_BASE_URL + "/types"; private static final String SPECIFIC_DEVICE_TYPE_ACTIONS_URL = DEVICE_TYPES_URL + "/{hid}/actions"; private static final String SPECIFIC_DEVICE_TYPE_ACTION_URL = SPECIFIC_DEVICE_TYPE_ACTIONS_URL + "/{index}"; private static final TypeReference<ListResultModel<DeviceActionTypeModel>> DEVICE_ACTION_TYPE_MODEL_TYPE_REF = new TypeReference<ListResultModel<DeviceActionTypeModel>>() { }; private static final TypeReference<ListResultModel<DeviceActionModel>> DEVICE_ACTION_MODEL_TYPE_REF = new TypeReference<ListResultModel<DeviceActionModel>>() { }; DeviceActionApi(ApiConfig apiConfig) { super(apiConfig); } /** * Sends GET request to obtain parameters of all available device action * types * * @return list of {@link DeviceActionTypeModel} containing action type * parameters * * @throws AcnClientException * if request failed */ public ListResultModel<DeviceActionTypeModel> listAvailableActionTypes() { String method = "listAvailableActionTypes"; try { URI uri = buildUri(ACTION_TYPES_URL); ListResultModel<DeviceActionTypeModel> result = execute(new HttpGet(uri), DEVICE_ACTION_TYPE_MODEL_TYPE_REF); logDebug(method, "size: %s", result.getSize()); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends GET request to obtain parameters of all available device actions * associated with specific device * * @param hid * String representing specific device * * @return list of {@link DeviceActionModel} containing action parameters * * @throws AcnClientException * if request failed */ public ListResultModel<DeviceActionModel> listDeviceActions(String hid) { String method = "listDeviceActions"; try { URI uri = buildUri(SPECIFIC_DEVICE_ACTIONS_URL.replace("{hid}", hid)); ListResultModel<DeviceActionModel> result = execute(new HttpGet(uri), DEVICE_ACTION_MODEL_TYPE_REF); logDebug(method, "size: %s", result.getSize()); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends POST request to create new action for specific device * * @param hid * {@link String} representing specific device * @param model * {@link DeviceActionModel} representing action parameters * * @return {@link HidModel} containing {@code hid} of action created * * @throws AcnClientException * if request failed */ public HidModel createNewDeviceAction(String hid, DeviceActionModel model) { String method = "createNewDeviceAction"; try { URI uri = buildUri(SPECIFIC_DEVICE_ACTIONS_URL.replace("{hid}", hid)); HidModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends DELETE request to remove action from specific device * * @param hid * {@link String} representing specific device * @param index * {@link Integer} representing index of action in actions list * * @return {@link HidModel} containing {@code hid} of action removed * * @throws AcnClientException * if request failed or action with specified {@code index} does * no exist */ public HidModel deleteDeviceAction(String hid, int index) { String method = "deleteDeviceAction"; try { URI uri = buildUri(SPECIFIC_ACTION_URL.replace("{hid}", hid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpDelete(uri), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends PUT request to update existing action for specific device * * @param hid * {@link String} representing specific device * @param index * {@link Integer} representing index of action in actions list * @param model * {@link DeviceActionModel} representing updated action * parameters * * @throws AcnClientException * if request failed */ public HidModel updateDeviceAction(String hid, int index, DeviceActionModel model) { String method = "updateDeviceAction"; try { URI uri = buildUri(SPECIFIC_ACTION_URL.replace("{hid}", hid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpPut(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } public ListResultModel<DeviceActionModel> listDeviceTypeActions(String deviceTypeHid) { String method = "listDeviceTypeActions"; try { URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTIONS_URL.replace("{hid}", deviceTypeHid)); ListResultModel<DeviceActionModel> result = execute(new HttpGet(uri), DEVICE_ACTION_MODEL_TYPE_REF); logDebug(method, "size: %s", result.getSize()); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } public HidModel createNewDeviceTypeAction(String deviceTypeHid, DeviceActionModel model) { String method = "createNewDeviceTypeAction"; try { URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTIONS_URL.replace("{hid}", deviceTypeHid)); HidModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } public HidModel deleteDeviceTypeAction(String deviceTypeHid, int index) { String method = "deleteDeviceTypeAction"; try { URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTION_URL.replace("{hid}", deviceTypeHid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpDelete(uri), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } public HidModel updateDeviceTypeAction(String deviceTypeHid, int index, DeviceActionModel model) { String method = "updateDeviceTypeAction"; try { URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTION_URL.replace("{hid}", deviceTypeHid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpPut(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } }
acn-client/src/main/java/com/arrow/acn/client/api/DeviceActionApi.java
/******************************************************************************* * Copyright (c) 2017 Arrow Electronics, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License 2.0 * which accompanies this distribution, and is available at * http://apache.org/licenses/LICENSE-2.0 * * Contributors: * Arrow Electronics, Inc. *******************************************************************************/ package com.arrow.acn.client.api; import java.net.URI; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import com.arrow.acn.client.AcnClientException; import com.arrow.acn.client.model.DeviceActionModel; import com.arrow.acn.client.model.DeviceActionTypeModel; import com.arrow.acs.JsonUtils; import com.arrow.acs.client.api.ApiConfig; import com.arrow.acs.client.model.HidModel; import com.arrow.acs.client.model.ListResultModel; import com.fasterxml.jackson.core.type.TypeReference; public class DeviceActionApi extends ApiAbstract { private static final String DEVICES_BASE_URL = API_BASE + "/devices"; private static final String ACTION_TYPES_URL = DEVICES_BASE_URL + "/actions/types"; private static final String SPECIFIC_DEVICE_URL = DEVICES_BASE_URL + "/{hid}"; private static final String SPECIFIC_DEVICE_ACTIONS_URL = SPECIFIC_DEVICE_URL + "/actions"; private static final String SPECIFIC_ACTION_URL = SPECIFIC_DEVICE_ACTIONS_URL + "/{index}"; private static final TypeReference<ListResultModel<DeviceActionTypeModel>> DEVICE_ACTION_TYPE_MODEL_TYPE_REF = new TypeReference<ListResultModel<DeviceActionTypeModel>>() { }; private static final TypeReference<ListResultModel<DeviceActionModel>> DEVICE_ACTION_MODEL_TYPE_REF = new TypeReference<ListResultModel<DeviceActionModel>>() { }; DeviceActionApi(ApiConfig apiConfig) { super(apiConfig); } /** * Sends GET request to obtain parameters of all available device action * types * * @return list of {@link DeviceActionTypeModel} containing action type * parameters * * @throws AcnClientException * if request failed */ public ListResultModel<DeviceActionTypeModel> listAvailableActionTypes() { String method = "listAvailableActionTypes"; try { URI uri = buildUri(ACTION_TYPES_URL); ListResultModel<DeviceActionTypeModel> result = execute(new HttpGet(uri), DEVICE_ACTION_TYPE_MODEL_TYPE_REF); logDebug(method, "size: %s", result.getSize()); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends GET request to obtain parameters of all available device actions * associated with specific device * * @param hid * String representing specific device * * @return list of {@link DeviceActionModel} containing action parameters * * @throws AcnClientException * if request failed */ public ListResultModel<DeviceActionModel> listDeviceActions(String hid) { String method = "listAvailableActionTypes"; try { URI uri = buildUri(SPECIFIC_DEVICE_ACTIONS_URL.replace("{hid}", hid)); ListResultModel<DeviceActionModel> result = execute(new HttpGet(uri), DEVICE_ACTION_MODEL_TYPE_REF); logDebug(method, "size: %s", result.getSize()); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends POST request to create new action for specific device * * @param hid * {@link String} representing specific device * @param model * {@link DeviceActionModel} representing action parameters * * @return {@link HidModel} containing {@code hid} of action created * * @throws AcnClientException * if request failed */ public HidModel createNewDeviceAction(String hid, DeviceActionModel model) { String method = "createNewDeviceAction"; try { URI uri = buildUri(SPECIFIC_DEVICE_ACTIONS_URL.replace("{hid}", hid)); HidModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends DELETE request to remove action from specific device * * @param hid * {@link String} representing specific device * @param index * {@link Integer} representing index of action in actions list * * @return {@link HidModel} containing {@code hid} of action removed * * @throws AcnClientException * if request failed or action with specified {@code index} does * no exist */ public HidModel deleteDeviceAction(String hid, int index) { String method = "findByHid"; try { URI uri = buildUri(SPECIFIC_ACTION_URL.replace("{hid}", hid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpDelete(uri), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } /** * Sends PUT request to update existing action for specific device * * @param hid * {@link String} representing specific device * @param index * {@link Integer} representing index of action in actions list * @param model * {@link DeviceActionModel} representing updated action * parameters * * @throws AcnClientException * if request failed */ public HidModel updateDeviceAction(String hid, int index, DeviceActionModel model) { String method = "updateDeviceAction"; try { URI uri = buildUri(SPECIFIC_ACTION_URL.replace("{hid}", hid).replace("{index}", Integer.toString(index))); HidModel result = execute(new HttpPut(uri), JsonUtils.toJson(model), HidModel.class); log(method, result); return result; } catch (Throwable e) { logError(method, e); throw new AcnClientException(method, e); } } }
KR-1740: add support of device action at device type level
acn-client/src/main/java/com/arrow/acn/client/api/DeviceActionApi.java
KR-1740: add support of device action at device type level
<ide><path>cn-client/src/main/java/com/arrow/acn/client/api/DeviceActionApi.java <ide> private static final String SPECIFIC_DEVICE_URL = DEVICES_BASE_URL + "/{hid}"; <ide> private static final String SPECIFIC_DEVICE_ACTIONS_URL = SPECIFIC_DEVICE_URL + "/actions"; <ide> private static final String SPECIFIC_ACTION_URL = SPECIFIC_DEVICE_ACTIONS_URL + "/{index}"; <add> private static final String DEVICE_TYPES_URL = DEVICES_BASE_URL + "/types"; <add> private static final String SPECIFIC_DEVICE_TYPE_ACTIONS_URL = DEVICE_TYPES_URL + "/{hid}/actions"; <add> private static final String SPECIFIC_DEVICE_TYPE_ACTION_URL = SPECIFIC_DEVICE_TYPE_ACTIONS_URL + "/{index}"; <ide> <ide> private static final TypeReference<ListResultModel<DeviceActionTypeModel>> DEVICE_ACTION_TYPE_MODEL_TYPE_REF = new TypeReference<ListResultModel<DeviceActionTypeModel>>() { <ide> }; <ide> * if request failed <ide> */ <ide> public ListResultModel<DeviceActionModel> listDeviceActions(String hid) { <del> String method = "listAvailableActionTypes"; <add> String method = "listDeviceActions"; <ide> try { <ide> URI uri = buildUri(SPECIFIC_DEVICE_ACTIONS_URL.replace("{hid}", hid)); <ide> ListResultModel<DeviceActionModel> result = execute(new HttpGet(uri), DEVICE_ACTION_MODEL_TYPE_REF); <ide> * no exist <ide> */ <ide> public HidModel deleteDeviceAction(String hid, int index) { <del> String method = "findByHid"; <add> String method = "deleteDeviceAction"; <ide> try { <ide> URI uri = buildUri(SPECIFIC_ACTION_URL.replace("{hid}", hid).replace("{index}", Integer.toString(index))); <ide> HidModel result = execute(new HttpDelete(uri), HidModel.class); <ide> throw new AcnClientException(method, e); <ide> } <ide> } <add> <add> public ListResultModel<DeviceActionModel> listDeviceTypeActions(String deviceTypeHid) { <add> String method = "listDeviceTypeActions"; <add> try { <add> URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTIONS_URL.replace("{hid}", deviceTypeHid)); <add> ListResultModel<DeviceActionModel> result = execute(new HttpGet(uri), DEVICE_ACTION_MODEL_TYPE_REF); <add> logDebug(method, "size: %s", result.getSize()); <add> return result; <add> } catch (Throwable e) { <add> logError(method, e); <add> throw new AcnClientException(method, e); <add> } <add> } <add> <add> public HidModel createNewDeviceTypeAction(String deviceTypeHid, DeviceActionModel model) { <add> String method = "createNewDeviceTypeAction"; <add> try { <add> URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTIONS_URL.replace("{hid}", deviceTypeHid)); <add> HidModel result = execute(new HttpPost(uri), JsonUtils.toJson(model), HidModel.class); <add> log(method, result); <add> return result; <add> } catch (Throwable e) { <add> logError(method, e); <add> throw new AcnClientException(method, e); <add> } <add> } <add> <add> public HidModel deleteDeviceTypeAction(String deviceTypeHid, int index) { <add> String method = "deleteDeviceTypeAction"; <add> try { <add> URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTION_URL.replace("{hid}", deviceTypeHid).replace("{index}", <add> Integer.toString(index))); <add> HidModel result = execute(new HttpDelete(uri), HidModel.class); <add> log(method, result); <add> return result; <add> } catch (Throwable e) { <add> logError(method, e); <add> throw new AcnClientException(method, e); <add> } <add> } <add> <add> public HidModel updateDeviceTypeAction(String deviceTypeHid, int index, DeviceActionModel model) { <add> String method = "updateDeviceTypeAction"; <add> try { <add> URI uri = buildUri(SPECIFIC_DEVICE_TYPE_ACTION_URL.replace("{hid}", deviceTypeHid).replace("{index}", <add> Integer.toString(index))); <add> HidModel result = execute(new HttpPut(uri), JsonUtils.toJson(model), HidModel.class); <add> log(method, result); <add> return result; <add> } catch (Throwable e) { <add> logError(method, e); <add> throw new AcnClientException(method, e); <add> } <add> } <ide> }
Java
apache-2.0
c649a574435d328f977cba953df2177e97ccdd4d
0
spinnaker/halyard,spinnaker/halyard,spinnaker/halyard
/* * Copyright 2017 Microsoft, 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.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.s3; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.AbstractPersistentStoreEditCommand; import com.netflix.spinnaker.halyard.cli.command.v1.config.providers.aws.AwsCommandProperties; import com.netflix.spinnaker.halyard.cli.ui.v1.AnsiUi; import com.netflix.spinnaker.halyard.config.model.v1.node.PersistentStore; import com.netflix.spinnaker.halyard.config.model.v1.persistentStorage.S3PersistentStore; import java.util.UUID; @Parameters(separators = "=") public class S3EditCommand extends AbstractPersistentStoreEditCommand<S3PersistentStore> { protected String getPersistentStoreType() { return PersistentStore.PersistentStoreType.S3.getId(); } @Parameter( names = "--bucket", description = "The name of a storage bucket that your specified account has access to. If not " + "specified, a random name will be chosen. If you specify a globally unique bucket name " + "that doesn't exist yet, Halyard will create that bucket for you." ) private String bucket; @Parameter( names = "--root-folder", description = "The root folder in the chosen bucket to place all of Spinnaker's persistent data in." ) private String rootFolder; @Parameter( names = "--endpoint", description = "An alternate endpoint that your S3-compatible storage can be found at. This is intended for " + "self-hosted storage services with S3-compatible APIs, e.g. Minio. If supplied, this storage type cannot be validated." ) private String endpoint; @Parameter( names = "--region", description = "This is only required if the bucket you specify doesn't exist yet. In that case, the " + "bucket will be created in that region. See http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region." ) private String region; @Parameter( names = "--assume-role", description = AwsCommandProperties.ASSUME_ROLE_DESCRIPTION ) private String assumeRole; @Parameter( names = "--access-key-id", description = AwsCommandProperties.ACCESS_KEY_ID_DESCRIPTION ) private String accessKeyId; @Parameter( names = "--secret-access-key", description = AwsCommandProperties.SECRET_KEY_DESCRIPTION, password = true ) private String secretAccessKey; @Override protected S3PersistentStore editPersistentStore(S3PersistentStore persistentStore) { if(isSet(bucket) && bucket.startsWith("s3://")){ bucket = bucket.substring(5); //Line to edit out the "s3://" part of the bucket string } persistentStore.setBucket(isSet(bucket) ? bucket : persistentStore.getBucket()); persistentStore.setRootFolder(isSet(rootFolder) ? rootFolder : persistentStore.getRootFolder()); persistentStore.setRegion(isSet(region) ? region : persistentStore.getRegion()); persistentStore.setEndpoint(isSet(endpoint) ? endpoint : persistentStore.getEndpoint()); persistentStore.setAccessKeyId(isSet(accessKeyId) ? accessKeyId : persistentStore.getAccessKeyId()); persistentStore.setSecretAccessKey(isSet(secretAccessKey) ? secretAccessKey : persistentStore.getSecretAccessKey()); if (persistentStore.getBucket() == null) { String bucketName = "spin-" + UUID.randomUUID().toString(); AnsiUi.raw("Generated bucket name: " + bucketName); persistentStore.setBucket(bucketName); } return persistentStore; } }
halyard-cli/src/main/java/com/netflix/spinnaker/halyard/cli/command/v1/config/persistentStorage/s3/S3EditCommand.java
/* * Copyright 2017 Microsoft, 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.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.s3; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.AbstractPersistentStoreEditCommand; import com.netflix.spinnaker.halyard.cli.command.v1.config.providers.aws.AwsCommandProperties; import com.netflix.spinnaker.halyard.cli.ui.v1.AnsiUi; import com.netflix.spinnaker.halyard.config.model.v1.node.PersistentStore; import com.netflix.spinnaker.halyard.config.model.v1.persistentStorage.S3PersistentStore; import java.util.UUID; @Parameters(separators = "=") public class S3EditCommand extends AbstractPersistentStoreEditCommand<S3PersistentStore> { protected String getPersistentStoreType() { return PersistentStore.PersistentStoreType.S3.getId(); } @Parameter( names = "--bucket", description = "The name of a storage bucket that your specified account has access to. If not " + "specified, a random name will be chosen. If you specify a globally unique bucket name " + "that doesn't exist yet, Halyard will create that bucket for you." ) private String bucket; @Parameter( names = "--root-folder", description = "The root folder in the chosen bucket to place all of Spinnaker's persistent data in." ) private String rootFolder; @Parameter( names = "--endpoint", description = "An alternate endpoint that your S3-compatible storage can be found at. This is intended for " + "self-hosted storage services with S3-compatible APIs, e.g. Minio. If supplied, this storage type cannot be validated." ) private String endpoint; @Parameter( names = "--region", description = "This is only required if the bucket you specify doesn't exist yet. In that case, the " + "bucket will be created in that region. See http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region." ) private String region; @Parameter( names = "--assume-role", description = AwsCommandProperties.ASSUME_ROLE_DESCRIPTION ) private String assumeRole; @Parameter( names = "--access-key-id", description = AwsCommandProperties.ACCESS_KEY_ID_DESCRIPTION ) private String accessKeyId; @Parameter( names = "--secret-access-key", description = AwsCommandProperties.SECRET_KEY_DESCRIPTION, password = true ) private String secretAccessKey; @Override protected S3PersistentStore editPersistentStore(S3PersistentStore persistentStore) { persistentStore.setBucket(isSet(bucket) ? bucket : persistentStore.getBucket()); persistentStore.setRootFolder(isSet(rootFolder) ? rootFolder : persistentStore.getRootFolder()); persistentStore.setRegion(isSet(region) ? region : persistentStore.getRegion()); persistentStore.setEndpoint(isSet(endpoint) ? endpoint : persistentStore.getEndpoint()); persistentStore.setAccessKeyId(isSet(accessKeyId) ? accessKeyId : persistentStore.getAccessKeyId()); persistentStore.setSecretAccessKey(isSet(secretAccessKey) ? secretAccessKey : persistentStore.getSecretAccessKey()); if (persistentStore.getBucket() == null) { String bucketName = "spin-" + UUID.randomUUID().toString(); AnsiUi.raw("Generated bucket name: " + bucketName); persistentStore.setBucket(bucketName); } return persistentStore; } }
fix(Halyard): s3 --bucket not accept s3:// prefix (#951) * fix(Halyard): s3 --bucket not accept s3:// prefix #951 Solution to "Halyard: s3 --bucket will not accetp s3:// prefix #2408" Better solution might be is to find out why the parameter cannot be stored with the s3:// because it should be needed to access the s3 bucket. Possibly the validate function cannot handle the s3:// prefix and the code needed when the bucket is accessed would need updating so this might be the easiest solution.
halyard-cli/src/main/java/com/netflix/spinnaker/halyard/cli/command/v1/config/persistentStorage/s3/S3EditCommand.java
fix(Halyard): s3 --bucket not accept s3:// prefix (#951)
<ide><path>alyard-cli/src/main/java/com/netflix/spinnaker/halyard/cli/command/v1/config/persistentStorage/s3/S3EditCommand.java <ide> <ide> @Override <ide> protected S3PersistentStore editPersistentStore(S3PersistentStore persistentStore) { <add> if(isSet(bucket) && bucket.startsWith("s3://")){ <add> bucket = bucket.substring(5); //Line to edit out the "s3://" part of the bucket string <add> } <ide> persistentStore.setBucket(isSet(bucket) ? bucket : persistentStore.getBucket()); <ide> persistentStore.setRootFolder(isSet(rootFolder) ? rootFolder : persistentStore.getRootFolder()); <ide> persistentStore.setRegion(isSet(region) ? region : persistentStore.getRegion());
JavaScript
mit
709eff1dae887ee546298aeff86803c79335f4af
0
Touffy/JSSCxml,Touffy/JSSCxml,Touffy/JSSCxml
// just declares datamodel variables as undefined SCxml.prototype.declare=function(element) { var c=element.firstElementChild if(element.tagName=="data") { var id=element.getAttribute("id") if(id in this.datamodel._jsscxml_predefined_) console.warn("Variable '"+id+"' is shadowing a predefined" + "window variable: please never delete it.\nin", element) else this.datamodel[id]=undefined } else while(c) { this.declare(c) c=c.nextElementSibling } } SCxml.prototype.assign=function(left, right) { if(left in this.datamodel._jsscxml_predefined_) this.datamodel._jsscxml_predefined_[left]=right else this.datamodel[left]=right } SCxml.prototype.readParams=function(element, data, alsoContent) { for(var c=element.firstElementChild; c; c=c.nextElementSibling) { if(c.tagName=="param"){ var name=c.getAttribute("name") var value=c.getAttribute("expr") || c.getAttribute("location") if(data.hasOwnProperty(name)) { if(data[name] instanceof Array) data[name].push(this.expr(value, c)) else data[name] = [data[name], this.expr(value, c)] } else data[name] = this.expr(value, c) } else if(alsoContent && c.tagName=="content"){ if(c.hasAttribute("expr")) data=this.expr(c.getAttribute("expr"), c) else data=c.textContent break } } return data } SCxml.parseTime=function (s) { s=/^((?:\d*\.)?\d+)(m?s)$/.exec(s) if(!s) return -1 var t=Number(s[1]) if(s[2]=="s") t*=1000 return t } // handles executable content, including custom namespaced (or not) SCxml.prototype.execute=function(element) { if(element.namespaceURI==this.dom.documentElement.namespaceURI){ if(element.localName in SCxml.executableContent) return SCxml.executableContent[element.localName](this, element) else if(element.localName in SCxml.executableContentNS.tolerate){ console.warn("executable element <"+element.tagName+"> should not use default namespace") return SCxml.executableContentNS.tolerate[element.localName](this, element) } else{ var c=element.firstElementChild while(c) { this.execute(c) c=c.nextElementSibling } } } else{ if(element.namespaceURI in SCxml.executableContentNS){ if(element.localName in SCxml.executableContentNS[element.namespaceURI]) return SCxml.executableContentNS[element.namespaceURI][element.localName](this, element) else console.warn("executable element <"+element.tagName+"> is not defined in namespace "+element.namespaceURI) } else if(element.localName in SCxml.executableContentNS.tolerate){ console.warn("executable element <"+element.tagName+"> should use its own namespace") return SCxml.executableContentNS.tolerate[element.localName](this, element) } else console.warn("missing executable content extension for namespace "+element.namespaceURI+" used with element <"+element.tagName+">") } } // if you want to add a custom executable element, add a property // to this object named for your namespace URI, and within that, // a method with the name of your element SCxml.executableContentNS={tolerate:{}} SCxml.executableContent={ raise: function(sc, element) { var event=element.getAttribute("event") ||sc.expr(element.getAttribute("eventexpr")) event=new SCxml.InternalEvent(event, element) sc.html.dispatchEvent(new CustomEvent("queue", {detail:event})) sc.internalQueue.push(event) }, send: function(sc, element) { if(sc.sendNoMore) return; // prevent <send> from terminated SCs var target=element.getAttribute("target") ||sc.expr(element.getAttribute("targetexpr"), element) var event=element.getAttribute("event") ||sc.expr(element.getAttribute("eventexpr"), element) if(!element.hasAttribute('id')) element.setAttribute('id', sc.uniqId()) var id=element.getAttribute("id"), loc if(loc=element.getAttribute("idlocation")) sc.expr(loc+'="'+id+'"') var proc=element.getAttribute("type") ||sc.expr(element.getAttribute("typeexpr"), element) ||"SCXML" var delay=SCxml.parseTime(element.getAttribute("delay") || sc.expr(element.getAttribute("delayexpr"), element)) if(target=="#_internal"){ var e=new SCxml.InternalEvent(event, element) sc.html.dispatchEvent(new CustomEvent("queue", {detail:e})) sc.internalQueue.push(e) return } if(proc in SCxml.EventProcessors) proc=SCxml.EventProcessors[proc] else for(var st in SCxml.EventProcessors) if(SCxml.EventProcessors[st].name==proc) proc=SCxml.EventProcessors[st] if("object" != typeof proc) sc.error("execution",element, new Error('unsupported IO processor "'+proc+'"')) var namelist=element.getAttribute("namelist") var data={} if(namelist) { namelist=namelist.split(" ") for(var i=0, name; name=namelist[i]; i++) data[name]=sc.expr(name) } data=sc.readParams(element, data, true) var e=proc.createEvent(event, sc, data, element) if(delay > -1) (element.sent || (element.sent=[])).push( new Delay(delay, !sc.paused, sc, proc, e, target, element)) else proc.send(e, target, element, sc) }, cancel: function(sc, element) { var id=element.getAttribute("sendid") ||sc.expr(element.getAttribute("sendidexpr")) for(var timer, sent=sc.dom.querySelector("send[id="+id+"]").sent; timer=sent.pop(); timer.cancel()); }, log: function(sc, element) { var value=element.getAttribute("expr") sc.log(element.getAttribute("label")+" = "+sc.expr(value,element)) }, data: function(sc, element) { var value=element.getAttribute("expr") var id=element.getAttribute("id") // create the variable first, so it's "declared" // even if the assignment part fails or doesn't occur if(id in sc.datamodel._jsscxml_predefined_) console.warn("Variable '"+id+"' is shadowing a predefined" + "window variable: please never delete it.\nin", element) else sc.datamodel[id]=undefined if(element.hasAttribute("expr")){ sc.expr(id+" = "+value, element) return } if(element.hasAttribute("src")) console.warn("You should use <fetch> instead of <data src>, which may render the interpreter unresponsive.") else if(value=element.firstElementChild){ // XML content if(value==element.lastElementChild){ var tmp=sc.dom.implementation.createDocument( value.namespaceURI, value.localName) for(var c=value.firstChild; c; c=c.nextSibling) tmp.documentElement.appendChild(tmp.importNode(c, true)) }else{ value=sc.dom.createDocumentFragment() for(var c=element.firstChild; c; c=c.nextSibling) value.appendChild(c.cloneNode(true)) } sc.assign(id, value) } else if(value=element.textContent){ // JS or normalized text content var tmp=sc.datamodel.syntexpr(value) // see if it is valid JS if(tmp instanceof sc.datamodel.SyntaxError) tmp=value.replace(/^\s*|\s*$/g, "").replace(/\s+/g," ") sc.assign(id, tmp) } }, assign: function(sc, element) { var value=element.getAttribute("expr") var loc=element.getAttribute("location") if(!loc) sc.error("syntax",element,new Error("'loc' attribute required")) value=sc.expr(loc+" = "+value, element) if(sc.expr(loc, element) != value) sc.error("execution",element,new Error("cannot assign to read-only property")) }, "if": function(sc, element) { var cond=sc.expr(element.getAttribute("cond")) var c=element.firstElementChild while(!cond && c) { if(c.tagName=="else") cond=true if(c.tagName=="elseif") cond=sc.expr(c.getAttribute("cond")) c=c.nextElementSibling } while(c) { if(c.tagName=="else" || c.tagName=="elseif") break sc.execute(c) c=c.nextElementSibling } }, foreach: function(sc, element) { var a=sc.expr(element.getAttribute("array")) var v=element.getAttribute("item") var i=element.getAttribute("index") if(("object"!=typeof a) && ("string"!=typeof a)) sc.error("execution",element,new TypeError("Invalid array")) if(i && !/^(\$|[^\W\d])[\w$]*$/.test(i)) sc.error("execution",element,new SyntaxError("Invalid index")) if(v && !/^(\$|[^\W\d])[\w$]*$/.test(v)) sc.error("execution",element,new SyntaxError("Invalid item")) for(var k in a) { if(i) sc.assign(i,k) if(v) sc.assign(v,a[k]) for(var c=element.firstElementChild; c; c=c.nextElementSibling) sc.execute(c) } }, script: function(sc, element) { sc.wrapScript(element.textContent,element) } }
SCxmlExecute.js
// just declares datamodel variables as undefined SCxml.prototype.declare=function(element) { var c=element.firstElementChild if(element.tagName=="data") { var id=element.getAttribute("id") if(id in this.datamodel._jsscxml_predefined_) console.warn("Variable '"+id+"' is shadowing a predefined" + "window variable: please never delete it.\nin", element) else this.datamodel[id]=undefined } else while(c) { this.declare(c) c=c.nextElementSibling } } SCxml.prototype.assign=function(left, right) { if(left in this.datamodel._jsscxml_predefined_) this.datamodel._jsscxml_predefined_[left]=right else this.datamodel[left]=right } SCxml.prototype.readParams=function(element, data, alsoContent) { for(var c=element.firstElementChild; c; c=c.nextElementSibling) { if(c.tagName=="param"){ var name=c.getAttribute("name") var value=c.getAttribute("expr") || c.getAttribute("location") if(data.hasOwnProperty(name)) { if(data[name] instanceof Array) data[name].push(this.expr(value, c)) else data[name] = [data[name], this.expr(value, c)] } else data[name] = this.expr(value, c) } else if(alsoContent && c.tagName=="content"){ if(c.hasAttribute("expr")) data=this.expr(c.getAttribute("expr"), c) else data=c.textContent break } } return data } SCxml.parseTime=function (s) { s=/^((?:\d*\.)?\d+)(m?s)$/.exec(s) if(!s) return -1 var t=Number(s[1]) if(s[2]=="s") t*=1000 return t } // handles executable content, including custom namespaced (or not) SCxml.prototype.execute=function(element) { if(element.namespaceURI==this.dom.documentElement.namespaceURI){ if(element.localName in SCxml.executableContent) return SCxml.executableContent[element.localName](this, element) else if(element.localName in SCxml.executableContentNS.tolerate){ console.warn("executable element <"+element.tagName+"> should not use default namespace") return SCxml.executableContentNS.tolerate[element.localName](this, element) } else{ var c=element.firstElementChild while(c) { this.execute(c) c=c.nextElementSibling } } } else{ if(element.namespaceURI in SCxml.executableContentNS){ if(element.localName in SCxml.executableContentNS[element.namespaceURI]) return SCxml.executableContentNS[element.namespaceURI][element.localName](this, element) else console.warn("executable element <"+element.tagName+"> is not defined in namespace "+element.namespaceURI) } else if(element.localName in SCxml.executableContentNS.tolerate){ console.warn("executable element <"+element.tagName+"> should use its own namespace") return SCxml.executableContentNS.tolerate[element.localName](this, element) } else console.warn("missing executable content extension for namespace "+element.namespaceURI+" used with element <"+element.tagName+">") } } // if you want to add a custom executable element, add a property // to this object named for your namespace URI, and within that, // a method with the name of your element SCxml.executableContentNS={tolerate:{}} SCxml.executableContent={ raise: function(sc, element) { var event=element.getAttribute("event") ||sc.expr(element.getAttribute("eventexpr")) event=new SCxml.InternalEvent(event, element) sc.html.dispatchEvent(new CustomEvent("queue", {detail:event})) sc.internalQueue.push(event) }, send: function(sc, element) { if(sc.sendNoMore) return; // prevent <send> from terminated SCs var target=element.getAttribute("target") ||sc.expr(element.getAttribute("targetexpr"), element) var event=element.getAttribute("event") ||sc.expr(element.getAttribute("eventexpr"), element) if(!element.hasAttribute('id')) element.setAttribute('id', sc.uniqId()) var id=element.getAttribute("id"), loc if(loc=element.getAttribute("idlocation")) sc.expr(loc+'="'+id+'"') var proc=element.getAttribute("type") ||sc.expr(element.getAttribute("typeexpr"), element) ||"SCXML" var delay=SCxml.parseTime(element.getAttribute("delay") || sc.expr(element.getAttribute("delayexpr"), element)) if(target=="#_internal"){ var e=new SCxml.InternalEvent(event, element) sc.html.dispatchEvent(new CustomEvent("queue", {detail:e})) sc.internalQueue.push(e) return } if(proc in SCxml.EventProcessors) proc=SCxml.EventProcessors[proc] else for(var st in SCxml.EventProcessors) if(SCxml.EventProcessors[st].name==proc) proc=SCxml.EventProcessors[st] if("object" != typeof proc) sc.error("execution",element, new Error('unsupported IO processor "'+proc+'"')) var namelist=element.getAttribute("namelist") var data={} if(namelist) { namelist=namelist.split(" ") for(var i=0, name; name=namelist[i]; i++) data[name]=sc.expr(name) } data=sc.readParams(element, data, true) var e=proc.createEvent(event, sc, data, element) if(delay > -1) (element.sent || (element.sent=[])).push( new Delay(delay, !sc.paused, sc, proc, e, target, element)) else proc.send(e, target, element, sc) }, cancel: function(sc, element) { var id=element.getAttribute("sendid") ||sc.expr(element.getAttribute("sendidexpr")) for(var timer, sent=sc.dom.querySelector("send[id="+id+"]").sent; timer=sent.pop(); timer.cancel()); }, log: function(sc, element) { var value=element.getAttribute("expr") sc.log(element.getAttribute("label")+" = "+sc.expr(value,element)) }, data: function(sc, element) { var value=element.getAttribute("expr") var id=element.getAttribute("id") // create the variable first, so it's "declared" // even if the assignment part fails or doesn't occur if(id in sc.datamodel._jsscxml_predefined_) console.warn("Variable '"+id+"' is shadowing a predefined" + "window variable: please never delete it.\nin", element) else sc.datamodel[id]=undefined if(element.hasAttribute("expr")){ sc.expr(id+" = "+value, element) return } if(element.hasAttribute("src")) console.warn("You should use <fetch> instead of <data src>, which may render the interpreter unresponsive.") else if(value=element.firstElementChild){ // XML content if(value==element.lastElementChild) value=new sc.datamodel.DOMParser().parse( new XMLSerializer().serializeToString(value)) else{ value=sc.dom.createDocumentFragment() for(var c=element.firstChild; c; c=c.nextSibling) value.appendChild(c.cloneNode(true)) } sc.assign(id, value) } else if(value=element.textContent){ // JS or normalized text content var tmp=sc.datamodel.syntexpr(value) // see if it is valid JS if(tmp instanceof sc.datamodel.SyntaxError) value=value.replace(/^\s*|\s*$/g, "").replace(/\s+/g," ") else value=tmp sc.assign(id, value) } }, assign: function(sc, element) { var value=element.getAttribute("expr") var loc=element.getAttribute("location") if(!loc) sc.error("syntax",element,new Error("'loc' attribute required")) value=sc.expr(loc+" = "+value, element) if(sc.expr(loc, element) != value) sc.error("execution",element,new Error("cannot assign to read-only property")) }, "if": function(sc, element) { var cond=sc.expr(element.getAttribute("cond")) var c=element.firstElementChild while(!cond && c) { if(c.tagName=="else") cond=true if(c.tagName=="elseif") cond=sc.expr(c.getAttribute("cond")) c=c.nextElementSibling } while(c) { if(c.tagName=="else" || c.tagName=="elseif") break sc.execute(c) c=c.nextElementSibling } }, foreach: function(sc, element) { var a=sc.expr(element.getAttribute("array")) var v=element.getAttribute("item") var i=element.getAttribute("index") if(("object"!=typeof a) && ("string"!=typeof a)) sc.error("execution",element,new TypeError("Invalid array")) if(i && !/^(\$|[^\W\d])[\w$]*$/.test(i)) sc.error("execution",element,new SyntaxError("Invalid index")) if(v && !/^(\$|[^\W\d])[\w$]*$/.test(v)) sc.error("execution",element,new SyntaxError("Invalid item")) for(var k in a) { if(i) sc.assign(i,k) if(v) sc.assign(v,a[k]) for(var c=element.firstElementChild; c; c=c.nextElementSibling) sc.execute(c) } }, script: function(sc, element) { sc.wrapScript(element.textContent,element) } }
fixed parsing of inline XML in <data>
SCxmlExecute.js
fixed parsing of inline XML in <data>
<ide><path>CxmlExecute.js <ide> if(element.hasAttribute("src")) <ide> console.warn("You should use <fetch> instead of <data src>, which may render the interpreter unresponsive.") <ide> else if(value=element.firstElementChild){ // XML content <del> if(value==element.lastElementChild) <del> value=new sc.datamodel.DOMParser().parse( <del> new XMLSerializer().serializeToString(value)) <del> else{ <add> if(value==element.lastElementChild){ <add> var tmp=sc.dom.implementation.createDocument( <add> value.namespaceURI, value.localName) <add> for(var c=value.firstChild; c; c=c.nextSibling) <add> tmp.documentElement.appendChild(tmp.importNode(c, true)) <add> }else{ <ide> value=sc.dom.createDocumentFragment() <ide> for(var c=element.firstChild; c; c=c.nextSibling) <ide> value.appendChild(c.cloneNode(true)) <ide> else if(value=element.textContent){ // JS or normalized text content <ide> var tmp=sc.datamodel.syntexpr(value) // see if it is valid JS <ide> if(tmp instanceof sc.datamodel.SyntaxError) <del> value=value.replace(/^\s*|\s*$/g, "").replace(/\s+/g," ") <del> else value=tmp <del> sc.assign(id, value) <add> tmp=value.replace(/^\s*|\s*$/g, "").replace(/\s+/g," ") <add> sc.assign(id, tmp) <ide> } <ide> }, <ide>
Java
apache-2.0
8422e69aba73dc9938590a64a155a8212d5c9493
0
mtransitapps/ca-grande-prairie-transit-bus-parser
package org.mtransit.parser.ca_grande_prairie_transit_bus; import static org.mtransit.commons.StringUtils.EMPTY; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.commons.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.mt.data.MAgency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; // https://data.cityofgp.com/Transportation/GP-Transit-GTFS-Feed/kwef-vsek // https://data.cityofgp.com/download/kwef-vsek/ZIP // http://jump.nextinsight.com/gtfs/ni_gp/google_transit.zip // https://gpt.mapstrat.com/current/google_transit.zip public class GrandePrairieTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@NotNull String[] args) { new GrandePrairieTransitBusAgencyTools().start(args); } @Nullable @Override public List<Locale> getSupportedLanguages() { return LANG_EN; } @Override public boolean defaultExcludeEnabled() { return true; } @NotNull @Override public String getAgencyName() { return "Grande Prairie Transit"; } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public boolean defaultRouteIdEnabled() { return true; } @Override public boolean useRouteShortNameForRouteId() { return true; } @Nullable @Override public Long convertRouteIdFromShortNameNotSupported(@NotNull String routeShortName) { if ("SJP".equalsIgnoreCase(routeShortName)) { return 8L; } else if ("SJS".equalsIgnoreCase(routeShortName)) { return 9L; } return null; } private static final Pattern STARTS_WITH_ROUTE_ = Pattern.compile("(^route )", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanRouteShortName(@NotNull String routeShortName) { routeShortName = STARTS_WITH_ROUTE_.matcher(routeShortName).replaceAll(EMPTY); return routeShortName; } @Override public boolean defaultRouteLongNameEnabled() { return true; } @Override public boolean defaultAgencyColorEnabled() { return true; } private static final String AGENCY_COLOR_GREEN = "056839"; // GREEN (from PNG logo) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public boolean directionSplitterEnabled(long routeId) { return false; // not useful because all loops } @Override public boolean directionFinderEnabled() { return true; } private static final Pattern ENDS_WITH_P_ = Pattern.compile("( \\(.+\\)$)"); @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { tripHeadsign = ENDS_WITH_P_.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanBounds(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern DASH_ = Pattern.compile("(^([^-]+)-([^-]+)$)", Pattern.CASE_INSENSITIVE); private static final String DASH_REPLACEMENT = "$2 - $3"; @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = DASH_.matcher(gStopName).replaceAll(DASH_REPLACEMENT); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } }
src/main/java/org/mtransit/parser/ca_grande_prairie_transit_bus/GrandePrairieTransitBusAgencyTools.java
package org.mtransit.parser.ca_grande_prairie_transit_bus; import static org.mtransit.commons.StringUtils.EMPTY; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.mtransit.commons.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.mt.data.MAgency; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; // https://data.cityofgp.com/Transportation/GP-Transit-GTFS-Feed/kwef-vsek // https://data.cityofgp.com/download/kwef-vsek/ZIP // http://jump.nextinsight.com/gtfs/ni_gp/google_transit.zip // https://gpt.mapstrat.com/current/google_transit.zip public class GrandePrairieTransitBusAgencyTools extends DefaultAgencyTools { public static void main(@NotNull String[] args) { new GrandePrairieTransitBusAgencyTools().start(args); } @Nullable @Override public List<Locale> getSupportedLanguages() { return LANG_EN; } @Override public boolean defaultExcludeEnabled() { return true; } @NotNull @Override public String getAgencyName() { return "Grande Prairie Transit"; } @NotNull @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public boolean defaultRouteIdEnabled() { return true; } @Override public boolean useRouteShortNameForRouteId() { return true; } @Nullable @Override public Long convertRouteIdFromShortNameNotSupported(@NotNull String routeShortName) { if ("SJP".equalsIgnoreCase(routeShortName)) { return 8L; } else if ("SJS".equalsIgnoreCase(routeShortName)) { return 9L; } return null; } private static final Pattern STARTS_WITH_ROUTE_ = Pattern.compile("(^route )", Pattern.CASE_INSENSITIVE); @NotNull @Override public String cleanRouteShortName(@NotNull String routeShortName) { routeShortName = STARTS_WITH_ROUTE_.matcher(routeShortName).replaceAll(EMPTY); return routeShortName; } @Override public boolean defaultRouteLongNameEnabled() { return true; } @Override public boolean defaultAgencyColorEnabled() { return true; } private static final String AGENCY_COLOR_GREEN = "056839"; // GREEN (from PNG logo) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @NotNull @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public boolean directionSplitterEnabled() { return false; // not useful because all loops } @Override public boolean directionFinderEnabled() { return true; } private static final Pattern ENDS_WITH_P_ = Pattern.compile("( \\(.+\\)$)"); @NotNull @Override public String cleanTripHeadsign(@NotNull String tripHeadsign) { tripHeadsign = ENDS_WITH_P_.matcher(tripHeadsign).replaceAll(EMPTY); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanBounds(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern DASH_ = Pattern.compile("(^([^-]+)-([^-]+)$)", Pattern.CASE_INSENSITIVE); private static final String DASH_REPLACEMENT = "$2 - $3"; @NotNull @Override public String cleanStopName(@NotNull String gStopName) { gStopName = DASH_.matcher(gStopName).replaceAll(DASH_REPLACEMENT); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); return CleanUtils.cleanLabel(gStopName); } }
Compatibility with latest update
src/main/java/org/mtransit/parser/ca_grande_prairie_transit_bus/GrandePrairieTransitBusAgencyTools.java
Compatibility with latest update
<ide><path>rc/main/java/org/mtransit/parser/ca_grande_prairie_transit_bus/GrandePrairieTransitBusAgencyTools.java <ide> } <ide> <ide> @Override <del> public boolean directionSplitterEnabled() { <add> public boolean directionSplitterEnabled(long routeId) { <ide> return false; // not useful because all loops <ide> } <ide>
Java
apache-2.0
fbce56b6a7f219beb328477500e3536b2240c01b
0
coinbase/coinbase-java,coinbase/coinbase-java,coinbase/coinbase-java
package com.coinbase.api; public class CoinbaseBuilder { String access_token; String api_key; String api_secret; String acct_id; /** * Build a new Coinbase client object with the specified options * * @return a new Coinbase client object */ public Coinbase build() throws Exception { return new CoinbaseImpl(this); } /** * Specify an access token to be used for authenticated requests * * Coinbase client objects built using an access token are thread-safe * * @param access_token the OAuth access token * * @return this CoinbaseBuilder object */ public CoinbaseBuilder withAccessToken(String access_token) { this.access_token = access_token; return this; } /** * Specify the HMAC api key and secret to be used for authenticated requests * * Having more than one client with the same api/secret globally is unsupported * and will result in sporadic auth errors as the nonce is calculated from the system time. * * @param api_key the HMAC API Key * @param api_secret the HMAC API Secret * * @return this CoinbaseBuilder object */ public CoinbaseBuilder withApiKey(String api_key, String api_secret) { this.api_key = api_key; this.api_secret = api_secret; return this; } /** * Specify the account id to be used for account-specific requests * * @param acct_id the account id * * @return this CoinbaseBuilder object */ public CoinbaseBuilder withAccountId(String acct_id) { this.acct_id = acct_id; return this; } }
src/main/java/com/coinbase/api/CoinbaseBuilder.java
package com.coinbase.api; public class CoinbaseBuilder { String access_token; String api_key; String api_secret; String acct_id; public Coinbase build() throws Exception { return new CoinbaseImpl(this); } public CoinbaseBuilder withAccessToken(String access_token) { this.access_token = access_token; return this; } public CoinbaseBuilder withApiKey(String api_key, String api_secret) { this.api_key = api_key; this.api_secret = api_secret; return this; } public CoinbaseBuilder withAccountId(String acct_id) { this.acct_id = acct_id; return this; } }
Added javadoc for CoinbaseBuilder
src/main/java/com/coinbase/api/CoinbaseBuilder.java
Added javadoc for CoinbaseBuilder
<ide><path>rc/main/java/com/coinbase/api/CoinbaseBuilder.java <ide> String api_secret; <ide> String acct_id; <ide> <add> /** <add> * Build a new Coinbase client object with the specified options <add> * <add> * @return a new Coinbase client object <add> */ <ide> public Coinbase build() throws Exception { <ide> return new CoinbaseImpl(this); <ide> } <ide> <add> /** <add> * Specify an access token to be used for authenticated requests <add> * <add> * Coinbase client objects built using an access token are thread-safe <add> * <add> * @param access_token the OAuth access token <add> * <add> * @return this CoinbaseBuilder object <add> */ <ide> public CoinbaseBuilder withAccessToken(String access_token) { <ide> this.access_token = access_token; <ide> return this; <ide> } <ide> <add> /** <add> * Specify the HMAC api key and secret to be used for authenticated requests <add> * <add> * Having more than one client with the same api/secret globally is unsupported <add> * and will result in sporadic auth errors as the nonce is calculated from the system time. <add> * <add> * @param api_key the HMAC API Key <add> * @param api_secret the HMAC API Secret <add> * <add> * @return this CoinbaseBuilder object <add> */ <ide> public CoinbaseBuilder withApiKey(String api_key, String api_secret) { <ide> this.api_key = api_key; <ide> this.api_secret = api_secret; <ide> return this; <ide> } <ide> <add> /** <add> * Specify the account id to be used for account-specific requests <add> * <add> * @param acct_id the account id <add> * <add> * @return this CoinbaseBuilder object <add> */ <ide> public CoinbaseBuilder withAccountId(String acct_id) { <ide> this.acct_id = acct_id; <ide> return this;
Java
epl-1.0
6f84e3a556f15018998b1eff9e1de486dac2f189
0
wo-amlangwang/ice,gorindn/ice,gorindn/ice,gorindn/ice,wo-amlangwang/ice,nickstanish/ice,menghanli/ice,gorindn/ice,eclipse/ice,menghanli/ice,wo-amlangwang/ice,menghanli/ice,nickstanish/ice,nickstanish/ice,eclipse/ice,wo-amlangwang/ice,gorindn/ice,nickstanish/ice,menghanli/ice,SmithRWORNL/ice,SmithRWORNL/ice,gorindn/ice,wo-amlangwang/ice,wo-amlangwang/ice,menghanli/ice,gorindn/ice,nickstanish/ice,menghanli/ice,wo-amlangwang/ice,SmithRWORNL/ice,wo-amlangwang/ice,eclipse/ice,eclipse/ice,menghanli/ice,eclipse/ice,SmithRWORNL/ice,SmithRWORNL/ice,eclipse/ice,SmithRWORNL/ice,nickstanish/ice,SmithRWORNL/ice,SmithRWORNL/ice,nickstanish/ice
package org.eclipse.ice.client.widgets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.ice.client.common.ActionTree; import org.eclipse.ice.client.widgets.viz.service.IPlot; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.forms.widgets.FormToolkit; /** * A {@code PlotGridComposite} is designed to display a grid of drawn * {@link IPlot}s. It includes widgets to customize the grid-based layout of the * plots. The order of a plot in the grid is based on its add order, and the * same plot can be added to the grid more than once. * * @author Jordan Deyton * */ public class PlotGridComposite extends Composite { /** * The {@code ToolBar} that contains widgets to update the grid layout and * clear the grid. */ private final ToolBar toolBar; /** * The grid of drawn plots. */ private final Composite gridComposite; /** * The user-customizable layout for {@link #gridComposite}, the grid of * drawn plots. */ private final GridLayout gridLayout; /** * The number of rows to display in the grid. */ private int rows = 2; /** * The number of columns to display in the grid. */ private int columns = 2; /** * This is a button used to close the drawn plot over which the mouse is * currently hovering. It should only be visible in the top-right corner of * a drawn plot when the mouse cursor is over the plot. */ private Button closeButton; /** * The listener responsible for showing and hiding the {@link #closeButton}. */ private final Listener plotHoverListener; /** * The list of currently drawn plots. This list is used to maintain the * insertion order. A nested class, {@link DrawnPlot}, is used to contain * meta-data about each drawn plot or cell in the grid. */ private final List<DrawnPlot> drawnPlots; /** * A map containing the currently drawn plots and their indices in * {@link #drawnPlots}. This is used for relatively fast removal based on a * reference to a drawn plot. */ private final Map<DrawnPlot, Integer> drawnPlotMap; /** * A dispose listener that will remove the disposed {@link DrawnPlot} * completely. */ private final DisposeListener plotDisposeListener = new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { removePlot((DrawnPlot) e.widget, true); } }; /** * The toolkit used to decorate SWT components. May be null. */ private final FormToolkit toolkit; /** * The default constructor. Creates a {@code Composite} designed to display * a grid of {@link IPlot} renderings. * * @param parent * A widget that will be the parent of the new instance (cannot * be null). * @param style * The style of widget to construct. */ public PlotGridComposite(Composite parent, int style) { this(parent, style, null); } /** * The full constructor. Children of this {@code Composite} will be * decorated with the specified {@code FormToolkit}. * * @param parent * A widget that will be the parent of the new instance (cannot * be null). * @param style * The style of widget to construct. * @param toolkit * The toolkit used to decorate SWT components. */ public PlotGridComposite(Composite parent, int style, FormToolkit toolkit) { super(parent, style); // Set the form toolkit for decorating widgets in this Composite. this.toolkit = toolkit; adapt(this); // Initialize the list of drawn plots. drawnPlots = new ArrayList<DrawnPlot>(); drawnPlotMap = new HashMap<DrawnPlot, Integer>(); // Set up the ToolBar. toolBar = createToolBar(this); // Set up the Composite containing the grid of plots. gridComposite = new Composite(this, SWT.NONE); adapt(gridComposite); gridLayout = new GridLayout(); gridLayout.makeColumnsEqualWidth = true; gridComposite.setLayout(gridLayout); // Lay out this Composite. The ToolBar should be across the top, while // the Composite containing the plot grid should grab all available // space. GridData gridData; setLayout(new GridLayout()); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); toolBar.setLayoutData(gridData); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridComposite.setLayoutData(gridData); // Create the listener that creates the close button when the mouse // enters a plot Composite (in the grid). plotHoverListener = new Listener() { /** * The most recent plot that was entered, or null. */ private DrawnPlot lastPlot; @Override public void handleEvent(Event event) { // We only deal with Composites here. if (event.widget instanceof Composite) { // Determine the plot Composite that the mouse entered. Composite child = (Composite) event.widget; DrawnPlot plot = findDrawnPlot(child); // If the mouse entered a new plot Composite (or exited // one), then a change occurred and requires an update to // the close button. if (plot != lastPlot) { // If necessary, dispose the old close button. if (closeButton != null) { closeButton.dispose(); } // If a plot Composite (or one of its children) was // entered, create a new close button in it. if (plot != null) { closeButton = plot.createCloseButton(); // When the button is disposed, its reference should // be cleared. closeButton .addDisposeListener(new DisposeListener() { @Override public void widgetDisposed( DisposeEvent e) { closeButton = null; } }); } // Set the reference to the most recently entered plot. lastPlot = plot; } } return; } }; // Add the listener as a filter so that it will be notified of *all* // SWT.MouseEnter events. This listener *must* be removed when this plot // grid is disposed. getDisplay().addFilter(SWT.MouseEnter, plotHoverListener); return; } /** * A convenience method to use the {@link #toolkit}, if available, to * decorate a given {@code Composite}. */ private void adapt(Composite composite) { if (toolkit != null) { toolkit.adapt(composite); } } /** * Creates a {@code ToolBar} for this {@code Composite}. It includes the * following controls: * <ol> * <li>Grid rows and columns</li> * <li>A button to clear plots from the grid</li> * </ol> * * @param parent * The parent {@code Composite} in which to draw the * {@code ToolBar}. * @return The newly created {@code ToolBar}. */ private ToolBar createToolBar(Composite parent) { // Create and adapt the ToolBar first so that the default styles will be // passed down to the widgets created by the ToolBarManager. ToolBar toolBar = new ToolBar(parent, SWT.WRAP | SWT.FLAT | SWT.HORIZONTAL); adapt(toolBar); ToolBarManager toolBarManager = new ToolBarManager(toolBar); // Add a "Rows" label next to the row Spinner. LabelContribution rowLabel = new LabelContribution("rows.label"); rowLabel.setText("Rows:"); toolBarManager.add(rowLabel); // Add a Spinner for setting the grid rows to the ToolBarManager (this // requires a JFace ControlContribution). SpinnerContribution rowSpinner = new SpinnerContribution("rows.spinner"); rowSpinner.setMinimum(1); rowSpinner.setMaximum(4); rowSpinner.setSelection(rows); rowSpinner.setIncrement(1); rowSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { rows = ((Spinner) e.widget).getSelection(); refreshLayout(); } }); toolBarManager.add(rowSpinner); // Add a "Columns" label next to the row Spinner. LabelContribution columnLabel = new LabelContribution("columns.label"); columnLabel.setText("Columns:"); toolBarManager.add(columnLabel); // Add a Spinner for setting the grid columns to the ToolBarManager // (this requires a JFace ControlContribution). SpinnerContribution columnSpinner = new SpinnerContribution( "columns.spinner"); columnSpinner.setMinimum(1); columnSpinner.setMaximum(4); columnSpinner.setSelection(columns); columnSpinner.setIncrement(1); columnSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { columns = ((Spinner) e.widget).getSelection(); refreshLayout(); } }); toolBarManager.add(columnSpinner); // Add a separator between the spinners and the clear button. toolBarManager.add(new Separator()); // Add a ToolBar button to clear the plots. toolBarManager.add(new Action("Clear") { @Override public void run() { clearPlots(); } }); // Apply the ToolBarManager changes to the ToolBar. toolBarManager.update(true); return toolBar; } /** * Adds a plot to be drawn inside the plot grid. Note that the same plot can * be added more than once. * * @param plot * The plot to draw inside the grid. * @return The index of the plot in the grid, or -1 if the plot could not be * drawn. * @throws Exception * An exception is thrown if the {@link IPlot} implementation * cannot be rendered. */ public int addPlot(IPlot plot) throws Exception { int index = -1; // Proceed if the plot is not null and there is still space available in // the grid. if (plot != null && drawnPlots.size() < rows * columns) { // Try to get the available categories and plot types, then try to // plot the first available one. Map<String, String[]> plotTypes = plot.getPlotTypes(); // Find the first category and plot type. String category = null; String type = null; for (Entry<String, String[]> entry : plotTypes.entrySet()) { category = entry.getKey(); String[] types = entry.getValue(); if (category != null && types != null) { for (int i = 0; i < types.length && type == null; i++) { type = types[i]; } if (type != null) { break; } } } // If a category and type could be found, try to draw the plot in a // new cell in the grid. if (category != null && type != null) { // Create the basic plot Composite. final DrawnPlot drawnPlot = new DrawnPlot(gridComposite, plot); adapt(drawnPlot); // Try to draw the category and type. If the underlying IPlot // cannot draw, then dispose of the undrawn plot Composite. try { drawnPlot.draw(category, type); } catch (Exception e) { drawnPlot.dispose(); } // Add the drawn plot to the list. index = drawnPlots.size(); drawnPlots.add(drawnPlot); drawnPlotMap.put(drawnPlot, index); // When the drawn plot is disposed, make sure it is removed from // the list of drawn plots. drawnPlot.addDisposeListener(plotDisposeListener); // Set the layout data for the new drawn plot. It should grab // all available space in the gridComposite's layout. GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); drawnPlot.setLayoutData(gridData); // Since a new plot was added, refresh the grid layout. refreshLayout(); } } return index; } /** * Removes the drawn plot at the specified index in the grid. If t a drawn * plot was removed, then, at the end of this call, the grid layout will be * refreshed. * * @param index * The index of the drawn plot to remove. If invalid, nothing is * done. */ public void removePlot(int index) { // Check the index before passing on the removal request to the defacto // remove method. We should refresh the grid layout. if (index >= 0 && index < drawnPlots.size()) { removePlot(drawnPlots.get(index), true); } return; } /** * Removes the drawn plot completely, refreshing the layout if necessary. * <b>This should be the defacto way to remove a drawn plot</b>. <i>If the * code only has access to the drawn plot itself and not this method</i>, * then the plot should be disposed directly. * * @param drawnPlot * The drawn plot to remove (and, if necessary, dispose). * @param refreshLayout * Whether or not to refresh the layout after the plot is * removed. */ private void removePlot(DrawnPlot drawnPlot, boolean refreshLayout) { // The drawn plot is assumed to be valid. // Remove it from the book keeping (both the list and the map). int i = drawnPlotMap.remove(drawnPlot); drawnPlots.remove(i); for (; i < drawnPlots.size(); i++) { drawnPlotMap.put(drawnPlots.get(i), i); } // If necessary, dispose it. if (!drawnPlot.isDisposed()) { // We don't want to trigger this method again, so remove the plot // dispose listener first. drawnPlot.removeDisposeListener(plotDisposeListener); drawnPlot.dispose(); } // If necessary, refresh the layout. if (refreshLayout) { refreshLayout(); } return; } /** * Removes all renderings of the specified plot from the grid. If a drawn * plot was removed, then, at the end of this call, the grid layout will be * refreshed. * * @param plot * The plot whose renderings should be removed from the grid. If * invalid or not rendered, nothing is done. */ public void removePlots(IPlot plot) { // We can only process non-null plots. if (plot != null) { // Remove all drawn plots whose IPlot matches the specified plot. boolean refreshLayout = false; // We traverse backward in the list to reduce the length of // traversals in the main remove method. for (int i = drawnPlots.size() - 1; i >= 0; i--) { DrawnPlot drawnPlot = drawnPlots.get(i); if (drawnPlot.plot == plot) { removePlot(drawnPlot, false); refreshLayout = true; } } // Only refresh the layout if at least one composite was disposed. if (refreshLayout) { refreshLayout(); } } return; } /** * Removes all drawn plots from the grid. At the end of this call, the grid * layout will be refreshed. */ public void clearPlots() { // Remove all plots. We traverse backward in the list to reduce the // length of traversals in the main remove method. for (int i = drawnPlots.size() - 1; i >= 0; i--) { removePlot(drawnPlots.get(i), false); } // We should refresh the layout. refreshLayout(); return; } /** * Finds the ancestor plot for the specified child {@code Composite}. * * @param child * The child {@code Composite} from which to start the search. * This could even be the plot {@code Composite} itself. Assumed * not to be null. * @return The main plot {@code Composite} that is an ancestor of the child, * or {@code null} if one could not be found. */ private DrawnPlot findDrawnPlot(Composite child) { // This loop breaks when all ancestors have been searched OR when the // child plot Composite (whose parent is gridComposite) has been found. Composite parent = child.getParent(); while (parent != gridComposite && parent != null) { child = parent; parent = child.getParent(); } return (parent != null ? (DrawnPlot) child : null); } /** * Refreshes the {@link #gridLayout} and drawn plot {@code GridData} based * on the {@link #rows} and {@link #columns} and the number of drawn plots. */ private void refreshLayout() { // Remove all excess drawn plots. int limit = rows * columns; for (int i = drawnPlots.size() - 1; i >= limit; i--) { removePlot(drawnPlots.get(i), false); } // Reset all cells to only take up one grid cell. GridData gridData; for (DrawnPlot drawnPlot : drawnPlots) { gridData = (GridData) drawnPlot.getLayoutData(); gridData.verticalSpan = 1; } int size = drawnPlots.size(); // Set the user-defined number of columns. The rows are handled already // because we've removed all excess plots. gridLayout.numColumns = (size > columns ? columns : size); // If the last row has empty cells, then all of the cells directly above // those empty cells should grab the excess vertical space by updating // the verticalSpan property. int lastRowSize = size % columns; // We shouldn't do anything if the last row is full or if there is only // one row. if (lastRowSize > 0 && size > columns) { int lastIndex = size - 1 - lastRowSize; for (int i = 0; i < columns - lastRowSize; i++) { DrawnPlot drawnPlot = drawnPlots.get(lastIndex - i); gridData = (GridData) drawnPlot.getLayoutData(); gridData.verticalSpan = 2; } } // Refresh the grid layout. gridComposite.layout(); return; } /* * (non-Javadoc) * * @see org.eclipse.swt.widgets.Widget#dispose() */ @Override public void dispose() { // Remove the filter for the listener that creates the close button on // certain SWT.MouseEnter events. getDisplay().removeFilter(SWT.MouseEnter, plotHoverListener); // Clear the plots. There is no need to refresh the layout. for (int i = drawnPlots.size() - 1; i >= 0; i--) { removePlot(drawnPlots.get(i), false); } // Proceed with the normal dispose operation. super.dispose(); } /** * This nested class provides the {@code Composite} that immediately wraps a * rendering from an {@code IPlot} implementation. It handles all * plot-specific widgets and layouts for the associated {@link #plot}. * * @author Jordan Deyton * */ private class DrawnPlot extends Composite { /** * The {@link IPlot} instance/implementation that is drawn. */ public final IPlot plot; /** * The default constructor. Creates a container for an {@code IPlot} * instance with the {@code SWT.BORDER} style. * * @param parent * The parent in which to draw the plot. * @param plot * The {@code IPlot} instance that will be drawn. */ public DrawnPlot(Composite parent, IPlot plot) { this(parent, plot, SWT.BORDER); } /** * The full constructor that allows a custom style to be set. * * @param parent * The parent in which to draw the plot. * @param plot * The {@code IPlot} instance that will be drawn. * @param style * The style to use for this {@code Composite}. */ public DrawnPlot(Composite parent, IPlot plot, int style) { super(parent, style); this.plot = plot; createContextMenu(); // The plot Composite should have a FormLayout so that the close // button can be properly displayed in the top-right corner on // top of all other controls. Otherwise, this is effectively a // FillLayout. setLayout(new FormLayout()); return; } /** * Creates a context {@code Menu} for the drawn plot's main * {@code Composite}. It includes the following controls by default: * <ol> * <li>Remove Plot</li> * <li>Separator</li> * <li>Set Plot Type</li> * <li>Separator</li> * <li>Any implementation-specific plot actions...</li> * </ol> * It is up to the related {@code IPlot} implementation to take the * created {@code Menu} and add it to child {@code Composite}s or update * it. * * @return The JFace {@code MenuManager} for the context {@code Menu}. */ private MenuManager createContextMenu() { MenuManager contextMenuManager = new MenuManager(); contextMenuManager.createContextMenu(this); // Create an action to remove the moused-over or clicked plot // rendering. final Action removeAction = new Action("Remove") { @Override public void run() { dispose(); } }; contextMenuManager.add(removeAction); // Add a separator between the remove and set plot type MenuItems. contextMenuManager.add(new Separator()); // Create the root ActionTree for setting the plot category and // type. ActionTree plotTypeTree = new ActionTree("Set Plot Type"); try { // Add an ActionTree for each category, and then add ActionTree // leaf // nodes for each type. Map<String, String[]> plotTypes = plot.getPlotTypes(); for (Entry<String, String[]> entry : plotTypes.entrySet()) { String category = entry.getKey(); String[] types = entry.getValue(); if (category != null && types != null && types.length > 0) { // Create the category ActionTree. ActionTree categoryTree = new ActionTree(category); plotTypeTree.add(categoryTree); // Add all types to the category ActionTree. Each Action // should try to set the plot category and type of the // drawn // plot. final String categoryRef = category; for (String type : types) { final String typeRef = type; categoryTree.add(new ActionTree(new Action(type) { @Override public void run() { try { draw(categoryRef, typeRef); } catch (Exception e) { e.printStackTrace(); } } })); } } } } catch (Exception e) { e.printStackTrace(); } // Add the ActionTree to the context Menu. contextMenuManager.add(plotTypeTree.getContributionItem()); // Set the context Menu for the plot Composite. setMenu(contextMenuManager.getMenu()); return contextMenuManager; } /** * Attempts to draw the specified plot category and type with the * underlying {@link IPlot} implementation. * * @param category * The new plot category. * @param type * The new plot type. * @throws Exception * An exception is thrown if the underlying {@code IPlot} * implementation fails to draw or update. */ public void draw(String category, String type) throws Exception { plot.draw(category, type, this); refreshLayout(); } /** * Refreshes the drawn plot's layout, adding a new {@code FormData} to * any new child Composites. */ private void refreshLayout() { boolean changed = false; for (Control child : getChildren()) { if (child.getLayoutData() == null) { // Set up the child to fill the plot Composite. FormData formData = new FormData(); formData.top = new FormAttachment(0, 0); formData.bottom = new FormAttachment(100, 0); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); child.setLayoutData(formData); changed = true; } } layout(changed); return; } /** * Creates a new {@link #closeButton} in the corner of the drawn plot. * <p> * To get rid of the close button, simply dispose it. * {@link #closeButton} will automatically be set to {@code null}. * </p> */ public Button createCloseButton() { // Set up the close button. Button closeButton = new Button(this, SWT.FLAT | SWT.CENTER); closeButton.setText("X"); FontData[] smallFont = closeButton.getFont().getFontData(); for (FontData fd : smallFont) { fd.setHeight(7); } closeButton.setFont(new Font(getDisplay(), smallFont)); closeButton.setToolTipText("Close plot"); closeButton.pack(); // Set the location of the button to the upper right-hand corner of // the // plot Composite, and above all other children of the plot // Composite. FormData formData = new FormData(); formData.top = new FormAttachment(0, 0); formData.right = new FormAttachment(100, -4); closeButton.setLayoutData(formData); closeButton.moveAbove(null); layout(); // Add a selection listener on it to close the drawn plot. closeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { dispose(); } }); return closeButton; } } }
src/org.eclipse.ice.client.widgets/src/org/eclipse/ice/client/widgets/PlotGridComposite.java
package org.eclipse.ice.client.widgets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.eclipse.ice.client.common.ActionTree; import org.eclipse.ice.client.widgets.viz.service.IPlot; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.ui.forms.widgets.FormToolkit; /** * A {@code PlotGridComposite} is designed to display a grid of drawn * {@link IPlot}s. It includes widgets to customize the grid-based layout of the * plots. The order of a plot in the grid is based on its add order, and the * same plot can be added to the grid more than once. * * @author Jordan Deyton * */ public class PlotGridComposite extends Composite { /** * The {@code ToolBar} that contains widgets to update the grid layout and * clear the grid. */ private final ToolBar toolBar; /** * The grid of drawn plots. */ private final Composite gridComposite; /** * The user-customizable layout for {@link #gridComposite}, the grid of * drawn plots. */ private final GridLayout gridLayout; /** * The number of rows to display in the grid. */ private int rows = 2; /** * The number of columns to display in the grid. */ private int columns = 2; /** * This is a button used to close the drawn plot over which the mouse is * currently hovering. It should only be visible in the top-right corner of * a drawn plot when the mouse cursor is over the plot. */ private Button closeButton; /** * The listener responsible for showing and hiding the {@link #closeButton}. */ private final Listener plotHoverListener; /** * The list of currently drawn plots. A nested class, {@link DrawnPlot}, is * used to contain meta-data about each drawn plot or cell in the grid. */ private final List<DrawnPlot> drawnPlots; /** * The toolkit used to decorate SWT components. May be null. */ private final FormToolkit toolkit; /** * The default constructor. Creates a {@code Composite} designed to display * a grid of {@link IPlot} renderings. * * @param parent * A widget that will be the parent of the new instance (cannot * be null). * @param style * The style of widget to construct. */ public PlotGridComposite(Composite parent, int style) { this(parent, style, null); } /** * The full constructor. Children of this {@code Composite} will be * decorated with the specified {@code FormToolkit}. * * @param parent * A widget that will be the parent of the new instance (cannot * be null). * @param style * The style of widget to construct. * @param toolkit * The toolkit used to decorate SWT components. */ public PlotGridComposite(Composite parent, int style, FormToolkit toolkit) { super(parent, style); // Set the form toolkit for decorating widgets in this Composite. this.toolkit = toolkit; adapt(this); // Initialize the list of drawn plots. drawnPlots = new ArrayList<DrawnPlot>(); // Set up the ToolBar. toolBar = createToolBar(this); // Set up the Composite containing the grid of plots. gridComposite = new Composite(this, SWT.NONE); adapt(gridComposite); gridLayout = new GridLayout(); gridLayout.makeColumnsEqualWidth = true; gridComposite.setLayout(gridLayout); // Lay out this Composite. The ToolBar should be across the top, while // the Composite containing the plot grid should grab all available // space. GridData gridData; setLayout(new GridLayout()); gridData = new GridData(SWT.FILL, SWT.FILL, true, false); toolBar.setLayoutData(gridData); gridData = new GridData(SWT.FILL, SWT.FILL, true, true); gridComposite.setLayoutData(gridData); // Create the listener that creates the close button when the mouse // enters a plot Composite (in the grid). plotHoverListener = new Listener() { /** * The most recent plot Composite that was entered, or null. */ private Composite lastParent; @Override public void handleEvent(Event event) { // We only deal with Composites here. if (event.widget instanceof Composite) { // Determine the plot Composite that the mouse entered. Composite child = (Composite) event.widget; Composite plotAncestor = findPlotComposite(child); // If the mouse entered a new plot Composite (or exited // one), then a change occurred and requires an update to // the close button. if (plotAncestor != lastParent) { // If necessary, dispose the old close button. if (closeButton != null) { System.out.println("Disposing close button"); closeButton.dispose(); } // If a plot Composite (or one of its children) was // entered, create a new close button in it. if (plotAncestor != null) { System.out.println("Creating close button"); createCloseButton(plotAncestor); } // Set the reference to the most recently entered plot. lastParent = plotAncestor; } } return; } }; // Add the listener as a filter so that it will be notified of *all* // SWT.MouseEnter events. This listener *must* be removed when this plot // grid is disposed. getDisplay().addFilter(SWT.MouseEnter, plotHoverListener); return; } /** * A convenience method to use the {@link #toolkit}, if available, to * decorate a given {@code Composite}. */ private void adapt(Composite composite) { if (toolkit != null) { toolkit.adapt(composite); } } /** * Creates a {@code ToolBar} for this {@code Composite}. It includes the * following controls: * <ol> * <li>Grid rows and columns</li> * <li>A button to clear plots from the grid</li> * </ol> * * @param parent * The parent {@code Composite} in which to draw the * {@code ToolBar}. * @return The newly created {@code ToolBar}. */ private ToolBar createToolBar(Composite parent) { // Create and adapt the ToolBar first so that the default styles will be // passed down to the widgets created by the ToolBarManager. ToolBar toolBar = new ToolBar(parent, SWT.WRAP | SWT.FLAT | SWT.HORIZONTAL); adapt(toolBar); ToolBarManager toolBarManager = new ToolBarManager(toolBar); // Add a "Rows" label next to the row Spinner. LabelContribution rowLabel = new LabelContribution("rows.label"); rowLabel.setText("Rows:"); toolBarManager.add(rowLabel); // Add a Spinner for setting the grid rows to the ToolBarManager (this // requires a JFace ControlContribution). SpinnerContribution rowSpinner = new SpinnerContribution("rows.spinner"); rowSpinner.setMinimum(1); rowSpinner.setMaximum(4); rowSpinner.setSelection(rows); rowSpinner.setIncrement(1); rowSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { rows = ((Spinner) e.widget).getSelection(); refreshLayout(); } }); toolBarManager.add(rowSpinner); // Add a "Columns" label next to the row Spinner. LabelContribution columnLabel = new LabelContribution("columns.label"); columnLabel.setText("Columns:"); toolBarManager.add(columnLabel); // Add a Spinner for setting the grid columns to the ToolBarManager // (this requires a JFace ControlContribution). SpinnerContribution columnSpinner = new SpinnerContribution( "columns.spinner"); columnSpinner.setMinimum(1); columnSpinner.setMaximum(4); columnSpinner.setSelection(columns); columnSpinner.setIncrement(1); columnSpinner.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { columns = ((Spinner) e.widget).getSelection(); refreshLayout(); } }); toolBarManager.add(columnSpinner); // Add a separator between the spinners and the clear button. toolBarManager.add(new Separator()); // Add a ToolBar button to clear the plots. toolBarManager.add(new Action("Clear") { @Override public void run() { clearPlots(); } }); // Apply the ToolBarManager changes to the ToolBar. toolBarManager.update(true); return toolBar; } /** * Creates a context {@code Menu} for the specified {@code Composite} . It * includes the following controls by default: * <ol> * <li>Remove Plot</li> * <li>Separator</li> * <li>Set Plot Type</li> * <li>Separator</li> * <li>Any implementation-specific plot actions...</li> * </ol> * It is up to the related {@code IPlot} implementation to take the created * {@code Menu} and add it to child {@code Composite}s or update it. * * @param plotComposite * The plot {@code Composite} that will get the context * {@code Menu}. * * @return The JFace {@code MenuManager} for the context {@code Menu}. */ private MenuManager createContextMenu(final Composite plotComposite) { MenuManager contextMenuManager = new MenuManager(); contextMenuManager.createContextMenu(this); final DrawnPlot drawnPlot = drawnPlots .get(findPlotIndex(plotComposite)); // Create an action to remove the moused-over or clicked plot rendering. final Action removeAction = new Action("Remove") { @Override public void run() { removePlot(findPlotIndex(plotComposite)); } }; contextMenuManager.add(removeAction); // Add a separator between the remove and set plot type MenuItems. contextMenuManager.add(new Separator()); // Create the root ActionTree for setting the plot category and type. ActionTree plotTypeTree = new ActionTree("Set Plot Type"); try { // Add an ActionTree for each category, and then add ActionTree leaf // nodes for each type. Map<String, String[]> plotTypes = drawnPlot.plot.getPlotTypes(); for (Entry<String, String[]> entry : plotTypes.entrySet()) { String category = entry.getKey(); String[] types = entry.getValue(); if (category != null && types != null && types.length > 0) { // Create the category ActionTree. ActionTree categoryTree = new ActionTree(category); plotTypeTree.add(categoryTree); // Add all types to the category ActionTree. Each Action // should try to set the plot category and type of the drawn // plot. final String categoryRef = category; for (String type : types) { final String typeRef = type; categoryTree.add(new ActionTree(new Action(type) { @Override public void run() { try { drawnPlot.setPlotType(categoryRef, typeRef); } catch (Exception e) { e.printStackTrace(); } } })); } } } } catch (Exception e) { e.printStackTrace(); } // Add the ActionTree to the context Menu. contextMenuManager.add(plotTypeTree.getContributionItem()); // Set the context Menu for the specified plot Composite. plotComposite.setMenu(contextMenuManager.getMenu()); return contextMenuManager; } /** * Adds a plot to be drawn inside the plot grid. Note that the same plot can * be added more than once. * * @param plot * The plot to draw inside the grid. * @return The index of the plot in the grid, or -1 if the plot could not be * drawn. * @throws Exception * An exception is thrown if the {@link IPlot} implementation * cannot be rendered. */ public int addPlot(IPlot plot) throws Exception { int index = -1; // Proceed if the plot is not null and there is still space available in // the grid. if (plot != null && drawnPlots.size() < rows * columns) { // Try to get the available categories and plot types, then try to // plot the first available one. Map<String, String[]> plotTypes = plot.getPlotTypes(); // Find the first category and plot type. String category = null; String type = null; for (Entry<String, String[]> entry : plotTypes.entrySet()) { category = entry.getKey(); String[] types = entry.getValue(); if (category != null && types != null) { for (int i = 0; i < types.length && type == null; i++) { type = types[i]; } if (type != null) { break; } } } // If a category and type could be found, try to draw the plot in a // new cell in the grid. if (category != null && type != null) { // Create the basic plot Composite. final int plotIndex = drawnPlots.size(); final Composite plotComposite = new Composite(gridComposite, SWT.BORDER); plotComposite.setBackground(getDisplay().getSystemColor( SWT.COLOR_RED)); // Adapt the plot Composite's appearance to the defaults. adapt(plotComposite); // Try to create the plot rendering. DrawnPlot drawnPlot = new DrawnPlot(plot, plotComposite, category, type); // Add the drawn plot to the list. index = plotIndex; drawnPlots.add(drawnPlot); // Set up the layout and layout data for the new drawn plot. GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); drawnPlot.composite.setLayoutData(gridData); // The plot Composite should have a FormLayout so that the close // button can be properly displayed in the top-right corner on // top of all other controls. Otherwise, this is effectively a // FillLayout. plotComposite.setLayout(new FormLayout()); for (Control child : plotComposite.getChildren()) { // Set up the child to fill the plot Composite. FormData formData = new FormData(); formData.top = new FormAttachment(0, 0); formData.bottom = new FormAttachment(100, 0); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); child.setLayoutData(formData); } // Since a new plot was added, refresh the grid layout. refreshLayout(); } } return index; } /** * Removes the drawn plot at the specified index in the grid. * * @param index * The index of the drawn plot to remove. If invalid, nothing is * done. */ public void removePlot(int index) { if (index >= 0 && index < drawnPlots.size()) { // Pull the associated drawn plot from the list. DrawnPlot drawnPlot = drawnPlots.remove(index); // Dispose the plot's associated cell in the grid. drawnPlot.dispose(); // Since a plot was removed, refresh the grid layout. refreshLayout(); } return; } /** * Removes all renderings of the specified plot from the grid. * * @param plot * The plot whose renderings should be removed from the grid. If * invalid or not rendered, nothing is done. */ public void removeDrawnPlots(IPlot plot) { if (plot != null) { boolean compositeDisposed = false; Iterator<DrawnPlot> iterator = drawnPlots.iterator(); while (iterator.hasNext()) { DrawnPlot drawnPlot = iterator.next(); if (drawnPlot.plot == plot) { // Pull the drawn plot from the list, then dispose it. iterator.remove(); drawnPlot.dispose(); compositeDisposed = true; } } // If a Composite was removed, refresh the grid layout. if (compositeDisposed) { refreshLayout(); } } return; } /** * Removes all renderings from the grid. */ public void clearPlots() { if (!drawnPlots.isEmpty()) { // Dispose all of the cells in the grid. for (DrawnPlot drawnPlot : drawnPlots) { drawnPlot.dispose(); } // Clear the list of drawn plots. drawnPlots.clear(); // Since a Composite was removed, refresh the grid layout. refreshLayout(); } return; } /** * Creates a new {@link #closeButton} in the corner of the drawn plot. * <p> * To get rid of the close button, simply dispose it. {@link #closeButton} * will automatically be set to {@code null}. * </p> * * @param plotComposite * The main plot {@code Composite} on which to draw the close * button. */ private void createCloseButton(final Composite plotComposite) { // Set up the close button. closeButton = new Button(plotComposite, SWT.FLAT | SWT.CENTER); closeButton.setText("X"); FontData[] smallFont = closeButton.getFont().getFontData(); for (FontData fd : smallFont) { fd.setHeight(7); } closeButton.setFont(new Font(plotComposite.getDisplay(), smallFont)); closeButton.setToolTipText("Close plot"); closeButton.pack(); // Set the location of the button to the upper right-hand corner of the // plot Composite, and above all other children of the plot Composite. FormData formData = new FormData(); formData.top = new FormAttachment(0, 0); formData.right = new FormAttachment(100, -4); closeButton.setLayoutData(formData); closeButton.moveAbove(null); plotComposite.layout(); // Add a selection listener on it to close the drawn plot. closeButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { // Determine the actual drawn plot here so that the "bad" // performance of the linear search is performed only when the // user actually wants to remove the plot. removePlot(findPlotIndex(plotComposite)); } }); // When the button is disposed, its reference should be cleared. closeButton.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { closeButton = null; } }); return; } /** * Traverses {@link #drawnPlots} until one is found whose main plot * {@code Composite} matches the specified {@code Composite}. * * @param plotComposite * The main plot {@code Composite} to search for in the list of * drawn plots. * @return The index of the {@link DrawnPlot} associated with the plot * {@code Composite}, or -1 if one could not be found. */ private int findPlotIndex(Composite plotComposite) { // This loop breaks when all drawn plots have been checked OR when the // index is found. int index = -1; for (int i = 0; i < drawnPlots.size() && index == -1; i++) { if (plotComposite == drawnPlots.get(i).composite) { index = i; } } return index; } /** * Finds the ancestor plot {@code Composite} for the specified child * {@code Composite}. * * @param child * The child {@code Composite} from which to start the search. * This could even be the plot {@code Composite} itself. Assumed * not to be null. * @return The main plot {@code Composite} that is an ancestor of the child, * or {@code null} if one could not be found. */ private Composite findPlotComposite(Composite child) { // This loop breaks when all ancestors have been searched OR when the // child plot Composite (whose parent is gridComposite) has been found. Composite parent = child.getParent(); while (parent != gridComposite && parent != null) { child = parent; parent = child.getParent(); } return (parent != null ? child : null); } /** * Refreshes the {@link #gridLayout} and drawn plot {@code GridData} based * on the {@link #rows} and {@link #columns} and the number of drawn plots. */ private void refreshLayout() { // Remove all excess drawn plots. int limit = rows * columns; for (int i = drawnPlots.size() - 1; i >= limit; i--) { drawnPlots.remove(i).dispose(); } // Reset all cells to only take up one grid cell. GridData gridData; for (DrawnPlot drawnPlot : drawnPlots) { gridData = (GridData) drawnPlot.composite.getLayoutData(); gridData.verticalSpan = 1; } int size = drawnPlots.size(); // Set the user-defined number of columns. The rows are handled already // because we've removed all excess plots. gridLayout.numColumns = (size > columns ? columns : size); // If the last row has empty cells, then all of the cells directly above // those empty cells should grab the excess vertical space by updating // the verticalSpan property. int lastRowSize = size % columns; // We shouldn't do anything if the last row is full or if there is only // one row. if (lastRowSize > 0 && size > columns) { int lastIndex = size - 1 - lastRowSize; for (int i = 0; i < columns - lastRowSize; i++) { DrawnPlot drawnPlot = drawnPlots.get(lastIndex - i); gridData = (GridData) drawnPlot.composite.getLayoutData(); gridData.verticalSpan = 2; } } // Refresh the grid layout. gridComposite.layout(); return; } /* * (non-Javadoc) * * @see org.eclipse.swt.widgets.Widget#dispose() */ @Override public void dispose() { // Remove the filter for the listener that creates the close button on // certain SWT.MouseEnter events. getDisplay().removeFilter(SWT.MouseEnter, plotHoverListener); // Proceed with the normal dispose operation. super.dispose(); } /** * This nested class contains meta-data about each drawn plot. * * @author Jordan Deyton * */ private class DrawnPlot { /** * The {@link IPlot} instance/implementation that is drawn. */ public final IPlot plot; /** * A {@code Composite} that contains the rendering of the plot. This is * passed, as the parent, to * {@link IPlot#draw(String, String, Composite)}. */ public final Composite composite; /** * The current category. */ private String category; /** * The current type. */ private String type; /** * Creates a new {@code DrawnPlot} to manage the plot's meta-data and * renders the plot in the specified parent {@code Composite}. * * @param plot * The {@code IPlot} to be drawn. * @param composite * The plot {@code Composite} in which to draw the plot. * @param category * The initial category for the plot. * @param type * The initial type for the plot category. * @throws Exception * An exception may be thrown by the {@code IPlot} * implementation if the plot could not be drawn. */ public DrawnPlot(IPlot plot, Composite composite, String category, String type) throws Exception { this.plot = plot; // Set the reference to the plot Composite. this.composite = composite; // Create a default context Menu for the plot Composite. createContextMenu(this.composite); // Render the plot. try { plot.draw(category, type, composite); } catch (Exception e) { dispose(); throw e; } return; } /** * Sets the current category and type of the drawn plot. * * @param category * The new category for the plot. * @param type * The new type for the plot category. * @throws Exception * An exception may be thrown by the {@code IPlot} * implementation if the plot could not be drawn. */ public void setPlotType(String category, String type) throws Exception { // Only process new, non-null plot category and type. if (category != null && type != null && (!category.equals(this.category) || !type .equals(this.type))) { // Try to draw the plot with the new category and type. Note // that the parent and child Composites should remain the same. plot.draw(category, type, composite); } return; } /** * A convenience method to dispose of resources used by this drawn plot. */ public void dispose() { composite.dispose(); category = null; type = null; } } }
Changed DrawnPlot to a Composite. It now handles its own layout. Updated the methods that remove the drawn plots to go through a single method where possible. It uses a list (so PlotGridComposite clients can remove by insertion order) and a map (for fast removal when the DrawnPlot is known but not its index, primarily for internal use or when it is disposed). Signed-off-by: Jordan Deyton <[email protected]>
src/org.eclipse.ice.client.widgets/src/org/eclipse/ice/client/widgets/PlotGridComposite.java
Changed DrawnPlot to a Composite. It now handles its own layout.
<ide><path>rc/org.eclipse.ice.client.widgets/src/org/eclipse/ice/client/widgets/PlotGridComposite.java <ide> package org.eclipse.ice.client.widgets; <ide> <ide> import java.util.ArrayList; <del>import java.util.Iterator; <add>import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <ide> private final Listener plotHoverListener; <ide> <ide> /** <del> * The list of currently drawn plots. A nested class, {@link DrawnPlot}, is <del> * used to contain meta-data about each drawn plot or cell in the grid. <add> * The list of currently drawn plots. This list is used to maintain the <add> * insertion order. A nested class, {@link DrawnPlot}, is used to contain <add> * meta-data about each drawn plot or cell in the grid. <ide> */ <ide> private final List<DrawnPlot> drawnPlots; <add> /** <add> * A map containing the currently drawn plots and their indices in <add> * {@link #drawnPlots}. This is used for relatively fast removal based on a <add> * reference to a drawn plot. <add> */ <add> private final Map<DrawnPlot, Integer> drawnPlotMap; <add> <add> /** <add> * A dispose listener that will remove the disposed {@link DrawnPlot} <add> * completely. <add> */ <add> private final DisposeListener plotDisposeListener = new DisposeListener() { <add> @Override <add> public void widgetDisposed(DisposeEvent e) { <add> removePlot((DrawnPlot) e.widget, true); <add> } <add> }; <ide> <ide> /** <ide> * The toolkit used to decorate SWT components. May be null. <ide> <ide> // Initialize the list of drawn plots. <ide> drawnPlots = new ArrayList<DrawnPlot>(); <add> drawnPlotMap = new HashMap<DrawnPlot, Integer>(); <ide> <ide> // Set up the ToolBar. <ide> toolBar = createToolBar(this); <ide> plotHoverListener = new Listener() { <ide> <ide> /** <del> * The most recent plot Composite that was entered, or null. <add> * The most recent plot that was entered, or null. <ide> */ <del> private Composite lastParent; <add> private DrawnPlot lastPlot; <ide> <ide> @Override <ide> public void handleEvent(Event event) { <ide> if (event.widget instanceof Composite) { <ide> // Determine the plot Composite that the mouse entered. <ide> Composite child = (Composite) event.widget; <del> Composite plotAncestor = findPlotComposite(child); <add> DrawnPlot plot = findDrawnPlot(child); <ide> <ide> // If the mouse entered a new plot Composite (or exited <ide> // one), then a change occurred and requires an update to <ide> // the close button. <del> if (plotAncestor != lastParent) { <add> if (plot != lastPlot) { <ide> // If necessary, dispose the old close button. <ide> if (closeButton != null) { <del> System.out.println("Disposing close button"); <ide> closeButton.dispose(); <ide> } <ide> // If a plot Composite (or one of its children) was <ide> // entered, create a new close button in it. <del> if (plotAncestor != null) { <del> System.out.println("Creating close button"); <del> createCloseButton(plotAncestor); <add> if (plot != null) { <add> closeButton = plot.createCloseButton(); <add> // When the button is disposed, its reference should <add> // be cleared. <add> closeButton <add> .addDisposeListener(new DisposeListener() { <add> @Override <add> public void widgetDisposed( <add> DisposeEvent e) { <add> closeButton = null; <add> } <add> }); <ide> } <ide> // Set the reference to the most recently entered plot. <del> lastParent = plotAncestor; <add> lastPlot = plot; <ide> } <ide> <ide> } <ide> toolBarManager.update(true); <ide> <ide> return toolBar; <del> } <del> <del> /** <del> * Creates a context {@code Menu} for the specified {@code Composite} . It <del> * includes the following controls by default: <del> * <ol> <del> * <li>Remove Plot</li> <del> * <li>Separator</li> <del> * <li>Set Plot Type</li> <del> * <li>Separator</li> <del> * <li>Any implementation-specific plot actions...</li> <del> * </ol> <del> * It is up to the related {@code IPlot} implementation to take the created <del> * {@code Menu} and add it to child {@code Composite}s or update it. <del> * <del> * @param plotComposite <del> * The plot {@code Composite} that will get the context <del> * {@code Menu}. <del> * <del> * @return The JFace {@code MenuManager} for the context {@code Menu}. <del> */ <del> private MenuManager createContextMenu(final Composite plotComposite) { <del> MenuManager contextMenuManager = new MenuManager(); <del> contextMenuManager.createContextMenu(this); <del> <del> final DrawnPlot drawnPlot = drawnPlots <del> .get(findPlotIndex(plotComposite)); <del> <del> // Create an action to remove the moused-over or clicked plot rendering. <del> final Action removeAction = new Action("Remove") { <del> @Override <del> public void run() { <del> removePlot(findPlotIndex(plotComposite)); <del> } <del> }; <del> contextMenuManager.add(removeAction); <del> <del> // Add a separator between the remove and set plot type MenuItems. <del> contextMenuManager.add(new Separator()); <del> <del> // Create the root ActionTree for setting the plot category and type. <del> ActionTree plotTypeTree = new ActionTree("Set Plot Type"); <del> try { <del> // Add an ActionTree for each category, and then add ActionTree leaf <del> // nodes for each type. <del> Map<String, String[]> plotTypes = drawnPlot.plot.getPlotTypes(); <del> for (Entry<String, String[]> entry : plotTypes.entrySet()) { <del> String category = entry.getKey(); <del> String[] types = entry.getValue(); <del> <del> if (category != null && types != null && types.length > 0) { <del> // Create the category ActionTree. <del> ActionTree categoryTree = new ActionTree(category); <del> plotTypeTree.add(categoryTree); <del> <del> // Add all types to the category ActionTree. Each Action <del> // should try to set the plot category and type of the drawn <del> // plot. <del> final String categoryRef = category; <del> for (String type : types) { <del> final String typeRef = type; <del> categoryTree.add(new ActionTree(new Action(type) { <del> @Override <del> public void run() { <del> try { <del> drawnPlot.setPlotType(categoryRef, typeRef); <del> } catch (Exception e) { <del> e.printStackTrace(); <del> } <del> } <del> })); <del> } <del> } <del> } <del> } catch (Exception e) { <del> e.printStackTrace(); <del> } <del> // Add the ActionTree to the context Menu. <del> contextMenuManager.add(plotTypeTree.getContributionItem()); <del> <del> // Set the context Menu for the specified plot Composite. <del> plotComposite.setMenu(contextMenuManager.getMenu()); <del> <del> return contextMenuManager; <ide> } <ide> <ide> /** <ide> if (category != null && type != null) { <ide> <ide> // Create the basic plot Composite. <del> final int plotIndex = drawnPlots.size(); <del> final Composite plotComposite = new Composite(gridComposite, <del> SWT.BORDER); <del> plotComposite.setBackground(getDisplay().getSystemColor( <del> SWT.COLOR_RED)); <del> <del> // Adapt the plot Composite's appearance to the defaults. <del> adapt(plotComposite); <del> <del> // Try to create the plot rendering. <del> DrawnPlot drawnPlot = new DrawnPlot(plot, plotComposite, <del> category, type); <add> final DrawnPlot drawnPlot = new DrawnPlot(gridComposite, plot); <add> adapt(drawnPlot); <add> <add> // Try to draw the category and type. If the underlying IPlot <add> // cannot draw, then dispose of the undrawn plot Composite. <add> try { <add> drawnPlot.draw(category, type); <add> } catch (Exception e) { <add> drawnPlot.dispose(); <add> } <ide> <ide> // Add the drawn plot to the list. <del> index = plotIndex; <add> index = drawnPlots.size(); <ide> drawnPlots.add(drawnPlot); <del> <del> // Set up the layout and layout data for the new drawn plot. <add> drawnPlotMap.put(drawnPlot, index); <add> <add> // When the drawn plot is disposed, make sure it is removed from <add> // the list of drawn plots. <add> drawnPlot.addDisposeListener(plotDisposeListener); <add> <add> // Set the layout data for the new drawn plot. It should grab <add> // all available space in the gridComposite's layout. <ide> GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true); <del> drawnPlot.composite.setLayoutData(gridData); <del> // The plot Composite should have a FormLayout so that the close <del> // button can be properly displayed in the top-right corner on <del> // top of all other controls. Otherwise, this is effectively a <del> // FillLayout. <del> plotComposite.setLayout(new FormLayout()); <del> for (Control child : plotComposite.getChildren()) { <del> // Set up the child to fill the plot Composite. <del> FormData formData = new FormData(); <del> formData.top = new FormAttachment(0, 0); <del> formData.bottom = new FormAttachment(100, 0); <del> formData.left = new FormAttachment(0, 0); <del> formData.right = new FormAttachment(100, 0); <del> child.setLayoutData(formData); <del> } <add> drawnPlot.setLayoutData(gridData); <ide> <ide> // Since a new plot was added, refresh the grid layout. <ide> refreshLayout(); <ide> } <ide> <ide> /** <del> * Removes the drawn plot at the specified index in the grid. <add> * Removes the drawn plot at the specified index in the grid. If t a drawn <add> * plot was removed, then, at the end of this call, the grid layout will be <add> * refreshed. <ide> * <ide> * @param index <ide> * The index of the drawn plot to remove. If invalid, nothing is <ide> * done. <ide> */ <ide> public void removePlot(int index) { <del> <add> // Check the index before passing on the removal request to the defacto <add> // remove method. We should refresh the grid layout. <ide> if (index >= 0 && index < drawnPlots.size()) { <del> // Pull the associated drawn plot from the list. <del> DrawnPlot drawnPlot = drawnPlots.remove(index); <del> <del> // Dispose the plot's associated cell in the grid. <add> removePlot(drawnPlots.get(index), true); <add> } <add> return; <add> } <add> <add> /** <add> * Removes the drawn plot completely, refreshing the layout if necessary. <add> * <b>This should be the defacto way to remove a drawn plot</b>. <i>If the <add> * code only has access to the drawn plot itself and not this method</i>, <add> * then the plot should be disposed directly. <add> * <add> * @param drawnPlot <add> * The drawn plot to remove (and, if necessary, dispose). <add> * @param refreshLayout <add> * Whether or not to refresh the layout after the plot is <add> * removed. <add> */ <add> private void removePlot(DrawnPlot drawnPlot, boolean refreshLayout) { <add> // The drawn plot is assumed to be valid. <add> <add> // Remove it from the book keeping (both the list and the map). <add> int i = drawnPlotMap.remove(drawnPlot); <add> drawnPlots.remove(i); <add> for (; i < drawnPlots.size(); i++) { <add> drawnPlotMap.put(drawnPlots.get(i), i); <add> } <add> <add> // If necessary, dispose it. <add> if (!drawnPlot.isDisposed()) { <add> // We don't want to trigger this method again, so remove the plot <add> // dispose listener first. <add> drawnPlot.removeDisposeListener(plotDisposeListener); <ide> drawnPlot.dispose(); <del> <del> // Since a plot was removed, refresh the grid layout. <add> } <add> <add> // If necessary, refresh the layout. <add> if (refreshLayout) { <ide> refreshLayout(); <ide> } <ide> <ide> } <ide> <ide> /** <del> * Removes all renderings of the specified plot from the grid. <add> * Removes all renderings of the specified plot from the grid. If a drawn <add> * plot was removed, then, at the end of this call, the grid layout will be <add> * refreshed. <ide> * <ide> * @param plot <ide> * The plot whose renderings should be removed from the grid. If <ide> * invalid or not rendered, nothing is done. <ide> */ <del> public void removeDrawnPlots(IPlot plot) { <del> <add> public void removePlots(IPlot plot) { <add> // We can only process non-null plots. <ide> if (plot != null) { <del> boolean compositeDisposed = false; <del> <del> Iterator<DrawnPlot> iterator = drawnPlots.iterator(); <del> while (iterator.hasNext()) { <del> DrawnPlot drawnPlot = iterator.next(); <del> <add> // Remove all drawn plots whose IPlot matches the specified plot. <add> boolean refreshLayout = false; <add> // We traverse backward in the list to reduce the length of <add> // traversals in the main remove method. <add> for (int i = drawnPlots.size() - 1; i >= 0; i--) { <add> DrawnPlot drawnPlot = drawnPlots.get(i); <ide> if (drawnPlot.plot == plot) { <del> // Pull the drawn plot from the list, then dispose it. <del> iterator.remove(); <del> drawnPlot.dispose(); <del> compositeDisposed = true; <add> removePlot(drawnPlot, false); <add> refreshLayout = true; <ide> } <ide> } <del> <del> // If a Composite was removed, refresh the grid layout. <del> if (compositeDisposed) { <add> // Only refresh the layout if at least one composite was disposed. <add> if (refreshLayout) { <ide> refreshLayout(); <ide> } <ide> } <ide> } <ide> <ide> /** <del> * Removes all renderings from the grid. <add> * Removes all drawn plots from the grid. At the end of this call, the grid <add> * layout will be refreshed. <ide> */ <ide> public void clearPlots() { <del> <del> if (!drawnPlots.isEmpty()) { <del> <del> // Dispose all of the cells in the grid. <del> for (DrawnPlot drawnPlot : drawnPlots) { <del> drawnPlot.dispose(); <del> } <del> // Clear the list of drawn plots. <del> drawnPlots.clear(); <del> <del> // Since a Composite was removed, refresh the grid layout. <del> refreshLayout(); <del> } <add> // Remove all plots. We traverse backward in the list to reduce the <add> // length of traversals in the main remove method. <add> for (int i = drawnPlots.size() - 1; i >= 0; i--) { <add> removePlot(drawnPlots.get(i), false); <add> } <add> // We should refresh the layout. <add> refreshLayout(); <ide> <ide> return; <ide> } <ide> <ide> /** <del> * Creates a new {@link #closeButton} in the corner of the drawn plot. <del> * <p> <del> * To get rid of the close button, simply dispose it. {@link #closeButton} <del> * will automatically be set to {@code null}. <del> * </p> <del> * <del> * @param plotComposite <del> * The main plot {@code Composite} on which to draw the close <del> * button. <del> */ <del> private void createCloseButton(final Composite plotComposite) { <del> <del> // Set up the close button. <del> closeButton = new Button(plotComposite, SWT.FLAT | SWT.CENTER); <del> closeButton.setText("X"); <del> FontData[] smallFont = closeButton.getFont().getFontData(); <del> for (FontData fd : smallFont) { <del> fd.setHeight(7); <del> } <del> closeButton.setFont(new Font(plotComposite.getDisplay(), smallFont)); <del> closeButton.setToolTipText("Close plot"); <del> closeButton.pack(); <del> <del> // Set the location of the button to the upper right-hand corner of the <del> // plot Composite, and above all other children of the plot Composite. <del> FormData formData = new FormData(); <del> formData.top = new FormAttachment(0, 0); <del> formData.right = new FormAttachment(100, -4); <del> closeButton.setLayoutData(formData); <del> closeButton.moveAbove(null); <del> plotComposite.layout(); <del> <del> // Add a selection listener on it to close the drawn plot. <del> closeButton.addSelectionListener(new SelectionAdapter() { <del> @Override <del> public void widgetSelected(SelectionEvent e) { <del> // Determine the actual drawn plot here so that the "bad" <del> // performance of the linear search is performed only when the <del> // user actually wants to remove the plot. <del> removePlot(findPlotIndex(plotComposite)); <del> } <del> }); <del> <del> // When the button is disposed, its reference should be cleared. <del> closeButton.addDisposeListener(new DisposeListener() { <del> @Override <del> public void widgetDisposed(DisposeEvent e) { <del> closeButton = null; <del> } <del> }); <del> <del> return; <del> } <del> <del> /** <del> * Traverses {@link #drawnPlots} until one is found whose main plot <del> * {@code Composite} matches the specified {@code Composite}. <del> * <del> * @param plotComposite <del> * The main plot {@code Composite} to search for in the list of <del> * drawn plots. <del> * @return The index of the {@link DrawnPlot} associated with the plot <del> * {@code Composite}, or -1 if one could not be found. <del> */ <del> private int findPlotIndex(Composite plotComposite) { <del> // This loop breaks when all drawn plots have been checked OR when the <del> // index is found. <del> int index = -1; <del> for (int i = 0; i < drawnPlots.size() && index == -1; i++) { <del> if (plotComposite == drawnPlots.get(i).composite) { <del> index = i; <del> } <del> } <del> return index; <del> } <del> <del> /** <del> * Finds the ancestor plot {@code Composite} for the specified child <del> * {@code Composite}. <add> * Finds the ancestor plot for the specified child {@code Composite}. <ide> * <ide> * @param child <ide> * The child {@code Composite} from which to start the search. <ide> * @return The main plot {@code Composite} that is an ancestor of the child, <ide> * or {@code null} if one could not be found. <ide> */ <del> private Composite findPlotComposite(Composite child) { <add> private DrawnPlot findDrawnPlot(Composite child) { <ide> // This loop breaks when all ancestors have been searched OR when the <ide> // child plot Composite (whose parent is gridComposite) has been found. <ide> Composite parent = child.getParent(); <ide> child = parent; <ide> parent = child.getParent(); <ide> } <del> return (parent != null ? child : null); <add> return (parent != null ? (DrawnPlot) child : null); <ide> } <ide> <ide> /** <ide> // Remove all excess drawn plots. <ide> int limit = rows * columns; <ide> for (int i = drawnPlots.size() - 1; i >= limit; i--) { <del> drawnPlots.remove(i).dispose(); <add> removePlot(drawnPlots.get(i), false); <ide> } <ide> <ide> // Reset all cells to only take up one grid cell. <ide> GridData gridData; <ide> for (DrawnPlot drawnPlot : drawnPlots) { <del> gridData = (GridData) drawnPlot.composite.getLayoutData(); <add> gridData = (GridData) drawnPlot.getLayoutData(); <ide> gridData.verticalSpan = 1; <ide> } <ide> <ide> int lastIndex = size - 1 - lastRowSize; <ide> for (int i = 0; i < columns - lastRowSize; i++) { <ide> DrawnPlot drawnPlot = drawnPlots.get(lastIndex - i); <del> gridData = (GridData) drawnPlot.composite.getLayoutData(); <add> gridData = (GridData) drawnPlot.getLayoutData(); <ide> gridData.verticalSpan = 2; <ide> } <ide> } <ide> // certain SWT.MouseEnter events. <ide> getDisplay().removeFilter(SWT.MouseEnter, plotHoverListener); <ide> <add> // Clear the plots. There is no need to refresh the layout. <add> for (int i = drawnPlots.size() - 1; i >= 0; i--) { <add> removePlot(drawnPlots.get(i), false); <add> } <add> <ide> // Proceed with the normal dispose operation. <ide> super.dispose(); <ide> } <ide> <ide> /** <del> * This nested class contains meta-data about each drawn plot. <add> * This nested class provides the {@code Composite} that immediately wraps a <add> * rendering from an {@code IPlot} implementation. It handles all <add> * plot-specific widgets and layouts for the associated {@link #plot}. <ide> * <ide> * @author Jordan Deyton <ide> * <ide> */ <del> private class DrawnPlot { <add> private class DrawnPlot extends Composite { <ide> <ide> /** <ide> * The {@link IPlot} instance/implementation that is drawn. <ide> */ <ide> public final IPlot plot; <add> <ide> /** <del> * A {@code Composite} that contains the rendering of the plot. This is <del> * passed, as the parent, to <del> * {@link IPlot#draw(String, String, Composite)}. <add> * The default constructor. Creates a container for an {@code IPlot} <add> * instance with the {@code SWT.BORDER} style. <add> * <add> * @param parent <add> * The parent in which to draw the plot. <add> * @param plot <add> * The {@code IPlot} instance that will be drawn. <ide> */ <del> public final Composite composite; <del> <add> public DrawnPlot(Composite parent, IPlot plot) { <add> this(parent, plot, SWT.BORDER); <add> } <add> <ide> /** <del> * The current category. <add> * The full constructor that allows a custom style to be set. <add> * <add> * @param parent <add> * The parent in which to draw the plot. <add> * @param plot <add> * The {@code IPlot} instance that will be drawn. <add> * @param style <add> * The style to use for this {@code Composite}. <ide> */ <del> private String category; <add> public DrawnPlot(Composite parent, IPlot plot, int style) { <add> super(parent, style); <add> <add> this.plot = plot; <add> <add> createContextMenu(); <add> <add> // The plot Composite should have a FormLayout so that the close <add> // button can be properly displayed in the top-right corner on <add> // top of all other controls. Otherwise, this is effectively a <add> // FillLayout. <add> setLayout(new FormLayout()); <add> <add> return; <add> } <add> <ide> /** <del> * The current type. <add> * Creates a context {@code Menu} for the drawn plot's main <add> * {@code Composite}. It includes the following controls by default: <add> * <ol> <add> * <li>Remove Plot</li> <add> * <li>Separator</li> <add> * <li>Set Plot Type</li> <add> * <li>Separator</li> <add> * <li>Any implementation-specific plot actions...</li> <add> * </ol> <add> * It is up to the related {@code IPlot} implementation to take the <add> * created {@code Menu} and add it to child {@code Composite}s or update <add> * it. <add> * <add> * @return The JFace {@code MenuManager} for the context {@code Menu}. <ide> */ <del> private String type; <add> private MenuManager createContextMenu() { <add> MenuManager contextMenuManager = new MenuManager(); <add> contextMenuManager.createContextMenu(this); <add> <add> // Create an action to remove the moused-over or clicked plot <add> // rendering. <add> final Action removeAction = new Action("Remove") { <add> @Override <add> public void run() { <add> dispose(); <add> } <add> }; <add> contextMenuManager.add(removeAction); <add> <add> // Add a separator between the remove and set plot type MenuItems. <add> contextMenuManager.add(new Separator()); <add> <add> // Create the root ActionTree for setting the plot category and <add> // type. <add> ActionTree plotTypeTree = new ActionTree("Set Plot Type"); <add> try { <add> // Add an ActionTree for each category, and then add ActionTree <add> // leaf <add> // nodes for each type. <add> Map<String, String[]> plotTypes = plot.getPlotTypes(); <add> for (Entry<String, String[]> entry : plotTypes.entrySet()) { <add> String category = entry.getKey(); <add> String[] types = entry.getValue(); <add> <add> if (category != null && types != null && types.length > 0) { <add> // Create the category ActionTree. <add> ActionTree categoryTree = new ActionTree(category); <add> plotTypeTree.add(categoryTree); <add> <add> // Add all types to the category ActionTree. Each Action <add> // should try to set the plot category and type of the <add> // drawn <add> // plot. <add> final String categoryRef = category; <add> for (String type : types) { <add> final String typeRef = type; <add> categoryTree.add(new ActionTree(new Action(type) { <add> @Override <add> public void run() { <add> try { <add> draw(categoryRef, typeRef); <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } <add> } <add> })); <add> } <add> } <add> } <add> } catch (Exception e) { <add> e.printStackTrace(); <add> } <add> // Add the ActionTree to the context Menu. <add> contextMenuManager.add(plotTypeTree.getContributionItem()); <add> <add> // Set the context Menu for the plot Composite. <add> setMenu(contextMenuManager.getMenu()); <add> <add> return contextMenuManager; <add> } <ide> <ide> /** <del> * Creates a new {@code DrawnPlot} to manage the plot's meta-data and <del> * renders the plot in the specified parent {@code Composite}. <del> * <del> * @param plot <del> * The {@code IPlot} to be drawn. <del> * @param composite <del> * The plot {@code Composite} in which to draw the plot. <del> * @param category <del> * The initial category for the plot. <del> * @param type <del> * The initial type for the plot category. <del> * @throws Exception <del> * An exception may be thrown by the {@code IPlot} <del> * implementation if the plot could not be drawn. <del> */ <del> public DrawnPlot(IPlot plot, Composite composite, String category, <del> String type) throws Exception { <del> this.plot = plot; <del> <del> // Set the reference to the plot Composite. <del> this.composite = composite; <del> <del> // Create a default context Menu for the plot Composite. <del> createContextMenu(this.composite); <del> <del> // Render the plot. <del> try { <del> plot.draw(category, type, composite); <del> } catch (Exception e) { <del> dispose(); <del> throw e; <del> } <del> <del> return; <del> } <del> <del> /** <del> * Sets the current category and type of the drawn plot. <add> * Attempts to draw the specified plot category and type with the <add> * underlying {@link IPlot} implementation. <ide> * <ide> * @param category <del> * The new category for the plot. <add> * The new plot category. <ide> * @param type <del> * The new type for the plot category. <add> * The new plot type. <ide> * @throws Exception <del> * An exception may be thrown by the {@code IPlot} <del> * implementation if the plot could not be drawn. <add> * An exception is thrown if the underlying {@code IPlot} <add> * implementation fails to draw or update. <ide> */ <del> public void setPlotType(String category, String type) throws Exception { <del> // Only process new, non-null plot category and type. <del> if (category != null <del> && type != null <del> && (!category.equals(this.category) || !type <del> .equals(this.type))) { <del> <del> // Try to draw the plot with the new category and type. Note <del> // that the parent and child Composites should remain the same. <del> plot.draw(category, type, composite); <del> } <del> <add> public void draw(String category, String type) throws Exception { <add> plot.draw(category, type, this); <add> refreshLayout(); <add> } <add> <add> /** <add> * Refreshes the drawn plot's layout, adding a new {@code FormData} to <add> * any new child Composites. <add> */ <add> private void refreshLayout() { <add> boolean changed = false; <add> for (Control child : getChildren()) { <add> if (child.getLayoutData() == null) { <add> // Set up the child to fill the plot Composite. <add> FormData formData = new FormData(); <add> formData.top = new FormAttachment(0, 0); <add> formData.bottom = new FormAttachment(100, 0); <add> formData.left = new FormAttachment(0, 0); <add> formData.right = new FormAttachment(100, 0); <add> child.setLayoutData(formData); <add> changed = true; <add> } <add> } <add> layout(changed); <ide> return; <ide> } <ide> <ide> /** <del> * A convenience method to dispose of resources used by this drawn plot. <add> * Creates a new {@link #closeButton} in the corner of the drawn plot. <add> * <p> <add> * To get rid of the close button, simply dispose it. <add> * {@link #closeButton} will automatically be set to {@code null}. <add> * </p> <ide> */ <del> public void dispose() { <del> composite.dispose(); <del> category = null; <del> type = null; <add> public Button createCloseButton() { <add> <add> // Set up the close button. <add> Button closeButton = new Button(this, SWT.FLAT | SWT.CENTER); <add> closeButton.setText("X"); <add> FontData[] smallFont = closeButton.getFont().getFontData(); <add> for (FontData fd : smallFont) { <add> fd.setHeight(7); <add> } <add> closeButton.setFont(new Font(getDisplay(), smallFont)); <add> closeButton.setToolTipText("Close plot"); <add> closeButton.pack(); <add> <add> // Set the location of the button to the upper right-hand corner of <add> // the <add> // plot Composite, and above all other children of the plot <add> // Composite. <add> FormData formData = new FormData(); <add> formData.top = new FormAttachment(0, 0); <add> formData.right = new FormAttachment(100, -4); <add> closeButton.setLayoutData(formData); <add> closeButton.moveAbove(null); <add> layout(); <add> <add> // Add a selection listener on it to close the drawn plot. <add> closeButton.addSelectionListener(new SelectionAdapter() { <add> @Override <add> public void widgetSelected(SelectionEvent e) { <add> dispose(); <add> } <add> }); <add> <add> return closeButton; <ide> } <ide> } <ide> }
Java
agpl-3.0
c4e09781a9aae75416f39d82eca3d423307a92d0
0
pivotal-nathan-sentjens/tigase-xmpp-java,fanout/tigase-server,Smartupz/tigase-server,sourcebits-praveenkh/Tagase,f24-ag/tigase,caiyingyuan/tigase71,nate-sentjens/tigase-xmpp-java,pivotal-nathan-sentjens/tigase-xmpp-java,f24-ag/tigase,wangningbo/tigase-server,amikey/tigase-server,fanout/tigase-server,caiyingyuan/tigase71,fanout/tigase-server,f24-ag/tigase,fanout/tigase-server,Smartupz/tigase-server,f24-ag/tigase,amikey/tigase-server,Smartupz/tigase-server,Smartupz/tigase-server,amikey/tigase-server,caiyingyuan/tigase71,wangningbo/tigase-server,cgvarela/tigase-server,nate-sentjens/tigase-xmpp-java,caiyingyuan/tigase71,wangningbo/tigase-server,nate-sentjens/tigase-xmpp-java,wangningbo/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,pivotal-nathan-sentjens/tigase-xmpp-java,nate-sentjens/tigase-xmpp-java,sourcebits-praveenkh/Tagase,nate-sentjens/tigase-xmpp-java,cgvarela/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,cgvarela/tigase-server,pivotal-nathan-sentjens/tigase-xmpp-java,fanout/tigase-server,f24-ag/tigase,sourcebits-praveenkh/Tagase,cgvarela/tigase-server,Smartupz/tigase-server,cgvarela/tigase-server,fanout/tigase-server,sourcebits-praveenkh/Tagase,amikey/tigase-server,nate-sentjens/tigase-xmpp-java,wangningbo/tigase-server,sourcebits-praveenkh/Tagase,f24-ag/tigase,caiyingyuan/tigase71,amikey/tigase-server,Smartupz/tigase-server,wangningbo/tigase-server,caiyingyuan/tigase71,sourcebits-praveenkh/Tagase,amikey/tigase-server,cgvarela/tigase-server,wangningbo/tigase-server
/* * Tigase Jabber/XMPP Server * Copyright (C) 2004-2007 "Artur Hefczyc" <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. * * $Rev$ * Last modified by $Author$ * $Date$ */ package tigase.xmpp.impl; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.Map; import java.util.logging.Logger; import java.util.Comparator; import java.util.Collections; import tigase.server.Packet; import tigase.xmpp.Authorization; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.StanzaType; import tigase.xmpp.XMPPProcessor; import tigase.xmpp.XMPPProcessorIfc; import tigase.xmpp.XMPPPreprocessorIfc; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.XMPPException; import tigase.xml.Element; import tigase.db.NonAuthUserRepository; import static tigase.xmpp.impl.Privacy.*; /** * Describe class JabberIqPrivacy here. * * * Created: Mon Oct 9 18:18:11 2006 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc { /** * Private logger for class instancess. */ private static Logger log = Logger.getLogger("tigase.xmpp.impl.JabberIqPrivacy"); private static final String XMLNS = "jabber:iq:privacy"; private static final String ID = XMLNS; private static final String[] ELEMENTS = {"query"}; private static final String[] XMLNSS = {XMLNS}; private static final Element[] DISCO_FEATURES = { new Element("feature", new String[] {"var"}, new String[] {XMLNS}) }; public Element[] supDiscoFeatures(final XMPPResourceConnection session) { return DISCO_FEATURES; } private enum ITEM_TYPE { jid, group, subscription, all }; private enum ITEM_ACTION { allow, deny }; private enum ITEM_SUBSCRIPTIONS { both, to, from, none }; private static final Comparator<Element> compar = new Comparator<Element>() { public int compare(Element el1, Element el2) { String or1 = el1.getAttribute(ORDER); String or2 = el2.getAttribute(ORDER); return or1.compareTo(or2); } }; public String id() { return ID; } public String[] supElements() { return ELEMENTS; } public String[] supNamespaces() { return XMLNSS; } /** * <code>preProcess</code> method checks only incoming stanzas * so it doesn't check for presence-out at all. * * @param packet a <code>Packet</code> value * @param session a <code>XMPPResourceConnection</code> value * @param repo a <code>NonAuthUserRepository</code> value * @return a <code>boolean</code> value */ public boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results) { if (session == null || !session.isAuthorized()) { return false; } // end of if (session == null) try { Element list = Privacy.getActiveList(session); if (list == null && session.getSessionData("privacy-init") == null) { String lName = Privacy.getDefaultList(session); if (lName != null) { Privacy.setActiveList(session, lName); list = Privacy.getActiveList(session); } // end of if (lName != null) session.putSessionData("privacy-init", ""); } // end of if (lName == null) if (list != null) { List<Element> items = list.getChildren(); Collections.sort(items, compar); for (Element item: items) { boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttribute(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttribute(TYPE)); } // end of if (item.getAttribute(TYPE) != null) String value = item.getAttribute(VALUE); String from = packet.getElemFrom(); if (from != null) { switch (type) { case jid: type_matched = from.contains(value); break; case group: String[] groups = Roster.getBuddyGroups(session, from); if (groups != null) { for (String group: groups) { if (type_matched = group.equals(value)) { break; } // end of if (group.equals(value)) } // end of for (String group: groups) } break; case subscription: ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to: type_matched = Roster.isSubscribedTo(session, from); break; case from: type_matched = Roster.isSubscribedFrom(session, from); break; case none: type_matched = (!Roster.isSubscribedFrom(session, from) && !Roster.isSubscribedTo(session, from)); break; case both: type_matched = (Roster.isSubscribedFrom(session, from) && Roster.isSubscribedTo(session, from)); break; default: break; } // end of switch (subscr) break; case all: default: type_matched = true; break; } // end of switch (type) } else { if (type == ITEM_TYPE.all) { type_matched = true; } } // end of if (from != null) else if (!type_matched) { break; } // end of if (!type_matched) List<Element> elems = item.getChildren(); if (elems == null || elems.size() == 0) { elem_matched = true; } else { for (Element elem: elems) { if (elem.getName().equals("presence-in")) { if (packet.getElemName().equals("presence") && (packet.getType() == null || packet.getType() == StanzaType.unavailable)) { elem_matched = true; break; } } else { if (elem.getName().equals(packet.getElemName())) { elem_matched = true; break; } // end of if (elem.getName().equals(packet.getElemName())) } // end of if (elem.getName().equals("presence-in")) else } // end of for (Element elem: elems) } // end of else if (!elem_matched) { break; } // end of if (!elem_matched) ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttribute(ACTION)); switch (action) { case allow: return false; case deny: return true; default: break; } // end of switch (action) } // end of for (Element item: items) } // end of if (lName != null) } catch (NotAuthorizedException e) { // results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, // "You must authorize session first.", true)); } // end of try-catch return false; } public void process(final Packet packet, final XMPPResourceConnection session, final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String, Object> settings) throws XMPPException { if (session == null) { return; } // end of if (session == null) try { StanzaType type = packet.getType(); switch (type) { case get: processGetRequest(packet, session, results); break; case set: processSetRequest(packet, session, results); break; case result: // Ignore break; default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Request type is incorrect", false)); break; } // end of switch (type) } catch (NotAuthorizedException e) { log.warning( "Received privacy request but user session is not authorized yet: " + packet.getStringData()); results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must authorize session first.", true)); } // end of try-catch } private void processSetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results) throws NotAuthorizedException, XMPPException { List<Element> children = packet.getElemChildren("/iq/query"); if (children != null && children.size() == 1) { Element child = children.get(0); if (child.getName().equals("list")) { // Broken privacy implementation sends list without name set // instead of sending BAD_REQUEST error I can just assign // 'default' name here. String name = child.getAttribute(NAME); if (name == null || name.length() == 0) { child.setAttribute(NAME, "default"); } // end of if (name == null || name.length() == 0) Privacy.addList(session, child); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) if (child.getName().equals("default")) { Privacy.setDefaultList(session, child); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) if (child.getName().equals("active")) { Privacy.setActiveList(session, child.getAttribute(NAME)); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) } else { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Only 1 element is allowed in privacy set request.", true)); } // end of else } private void processGetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results) throws NotAuthorizedException, XMPPException { List<Element> children = packet.getElemChildren("/iq/query"); if (children == null || children.size() == 0) { String[] lists = Privacy.getLists(session); if (lists != null) { StringBuilder sblists = new StringBuilder(); for (String list : lists) { sblists.append("<list name=\"" + list + "\"/>"); } String list = Privacy.getDefaultList(session); if (list != null) { sblists.append("<default name=\"" + list + "\"/>"); } // end of if (defList != null) list = Privacy.getActiveListName(session); if (list != null) { sblists.append("<active name=\"" + list + "\"/>"); } // end of if (defList != null) results.offer(packet.okResult(sblists.toString(), 1)); } else { results.offer(packet.okResult((String)null, 1)); } // end of if (buddies != null) else } else { if (children.size() > 1) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "You can retrieve only one list at a time.", true)); } else { Element eList = Privacy.getList(session, children.get(0).getAttribute("name")); if (eList != null) { results.offer(packet.okResult(eList, 1)); } else { results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Requested list not found.", true)); } // end of if (eList != null) else } // end of else } // end of else } } // JabberIqPrivacy
src/main/java/tigase/xmpp/impl/JabberIqPrivacy.java
/* * Tigase Jabber/XMPP Server * Copyright (C) 2004-2007 "Artur Hefczyc" <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. Look for COPYING file in the top folder. * If not, see http://www.gnu.org/licenses/. * * $Rev$ * Last modified by $Author$ * $Date$ */ package tigase.xmpp.impl; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.Map; import java.util.logging.Logger; import java.util.Comparator; import java.util.Collections; import tigase.server.Packet; import tigase.xmpp.Authorization; import tigase.xmpp.NotAuthorizedException; import tigase.xmpp.StanzaType; import tigase.xmpp.XMPPProcessor; import tigase.xmpp.XMPPProcessorIfc; import tigase.xmpp.XMPPPreprocessorIfc; import tigase.xmpp.XMPPResourceConnection; import tigase.xmpp.XMPPException; import tigase.xml.Element; import tigase.db.NonAuthUserRepository; import static tigase.xmpp.impl.Privacy.*; /** * Describe class JabberIqPrivacy here. * * * Created: Mon Oct 9 18:18:11 2006 * * @author <a href="mailto:[email protected]">Artur Hefczyc</a> * @version $Rev$ */ public class JabberIqPrivacy extends XMPPProcessor implements XMPPProcessorIfc, XMPPPreprocessorIfc { /** * Private logger for class instancess. */ private static Logger log = Logger.getLogger("tigase.xmpp.impl.JabberIqPrivacy"); private static final String XMLNS = "jabber:iq:privacy"; private static final String ID = XMLNS; private static final String[] ELEMENTS = {"query"}; private static final String[] XMLNSS = {XMLNS}; private static final Element[] DISCO_FEATURES = { new Element("feature", new String[] {"var"}, new String[] {XMLNS}) }; public Element[] supDiscoFeatures(final XMPPResourceConnection session) { return DISCO_FEATURES; } private enum ITEM_TYPE { jid, group, subscription, all }; private enum ITEM_ACTION { allow, deny }; private enum ITEM_SUBSCRIPTIONS { both, to, from, none }; private static final Comparator<Element> compar = new Comparator<Element>() { public int compare(Element el1, Element el2) { String or1 = el1.getAttribute(ORDER); String or2 = el2.getAttribute(ORDER); return or1.compareTo(or2); } }; public String id() { return ID; } public String[] supElements() { return ELEMENTS; } public String[] supNamespaces() { return XMLNSS; } /** * <code>preProcess</code> method checks only incoming stanzas * so it doesn't check for presence-out at all. * * @param packet a <code>Packet</code> value * @param session a <code>XMPPResourceConnection</code> value * @param repo a <code>NonAuthUserRepository</code> value * @return a <code>boolean</code> value */ public boolean preProcess(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results) { if (session == null || !session.isAuthorized()) { return false; } // end of if (session == null) try { Element list = Privacy.getActiveList(session); if (list == null && session.getSessionData("privacy-init") == null) { String lName = Privacy.getDefaultList(session); if (lName != null) { Privacy.setActiveList(session, lName); list = Privacy.getActiveList(session); } // end of if (lName != null) session.putSessionData("privacy-init", ""); } // end of if (lName == null) if (list != null) { List<Element> items = list.getChildren(); Collections.sort(items, compar); for (Element item: items) { boolean type_matched = false; boolean elem_matched = false; ITEM_TYPE type = ITEM_TYPE.all; if (item.getAttribute(TYPE) != null) { type = ITEM_TYPE.valueOf(item.getAttribute(TYPE)); } // end of if (item.getAttribute(TYPE) != null) String value = item.getAttribute(VALUE); String from = packet.getElemFrom(); if (from != null) { switch (type) { case jid: type_matched = from.contains(value); break; case group: String[] groups = Roster.getBuddyGroups(session, from); for (String group: groups) { if (type_matched = group.equals(value)) { break; } // end of if (group.equals(value)) } // end of for (String group: groups) break; case subscription: ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value); switch (subscr) { case to: type_matched = Roster.isSubscribedTo(session, from); break; case from: type_matched = Roster.isSubscribedFrom(session, from); break; case none: type_matched = (!Roster.isSubscribedFrom(session, from) && !Roster.isSubscribedTo(session, from)); break; case both: type_matched = (Roster.isSubscribedFrom(session, from) && Roster.isSubscribedTo(session, from)); break; default: break; } // end of switch (subscr) break; case all: default: type_matched = true; break; } // end of switch (type) } else { if (type == ITEM_TYPE.all) { type_matched = true; } } // end of if (from != null) else if (!type_matched) { break; } // end of if (!type_matched) List<Element> elems = item.getChildren(); if (elems == null || elems.size() == 0) { elem_matched = true; } else { for (Element elem: elems) { if (elem.getName().equals("presence-in")) { if (packet.getElemName().equals("presence") && (packet.getType() == null || packet.getType() == StanzaType.unavailable)) { elem_matched = true; break; } } else { if (elem.getName().equals(packet.getElemName())) { elem_matched = true; break; } // end of if (elem.getName().equals(packet.getElemName())) } // end of if (elem.getName().equals("presence-in")) else } // end of for (Element elem: elems) } // end of else if (!elem_matched) { break; } // end of if (!elem_matched) ITEM_ACTION action = ITEM_ACTION.valueOf(item.getAttribute(ACTION)); switch (action) { case allow: return false; case deny: return true; default: break; } // end of switch (action) } // end of for (Element item: items) } // end of if (lName != null) } catch (NotAuthorizedException e) { // results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, // "You must authorize session first.", true)); } // end of try-catch return false; } public void process(final Packet packet, final XMPPResourceConnection session, final NonAuthUserRepository repo, final Queue<Packet> results, final Map<String, Object> settings) throws XMPPException { if (session == null) { return; } // end of if (session == null) try { StanzaType type = packet.getType(); switch (type) { case get: processGetRequest(packet, session, results); break; case set: processSetRequest(packet, session, results); break; case result: // Ignore break; default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Request type is incorrect", false)); break; } // end of switch (type) } catch (NotAuthorizedException e) { log.warning( "Received privacy request but user session is not authorized yet: " + packet.getStringData()); results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must authorize session first.", true)); } // end of try-catch } private void processSetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results) throws NotAuthorizedException, XMPPException { List<Element> children = packet.getElemChildren("/iq/query"); if (children != null && children.size() == 1) { Element child = children.get(0); if (child.getName().equals("list")) { // Broken privacy implementation sends list without name set // instead of sending BAD_REQUEST error I can just assign // 'default' name here. String name = child.getAttribute(NAME); if (name == null || name.length() == 0) { child.setAttribute(NAME, "default"); } // end of if (name == null || name.length() == 0) Privacy.addList(session, child); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) if (child.getName().equals("default")) { Privacy.setDefaultList(session, child); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) if (child.getName().equals("active")) { Privacy.setActiveList(session, child.getAttribute(NAME)); results.offer(packet.okResult((String)null, 0)); } // end of if (child.getName().equals("list)) } else { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Only 1 element is allowed in privacy set request.", true)); } // end of else } private void processGetRequest(final Packet packet, final XMPPResourceConnection session, final Queue<Packet> results) throws NotAuthorizedException, XMPPException { List<Element> children = packet.getElemChildren("/iq/query"); if (children == null || children.size() == 0) { String[] lists = Privacy.getLists(session); if (lists != null) { StringBuilder sblists = new StringBuilder(); for (String list : lists) { sblists.append("<list name=\"" + list + "\"/>"); } String list = Privacy.getDefaultList(session); if (list != null) { sblists.append("<default name=\"" + list + "\"/>"); } // end of if (defList != null) list = Privacy.getActiveListName(session); if (list != null) { sblists.append("<active name=\"" + list + "\"/>"); } // end of if (defList != null) results.offer(packet.okResult(sblists.toString(), 1)); } else { results.offer(packet.okResult((String)null, 1)); } // end of if (buddies != null) else } else { if (children.size() > 1) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "You can retrieve only one list at a time.", true)); } else { Element eList = Privacy.getList(session, children.get(0).getAttribute("name")); if (eList != null) { results.offer(packet.okResult(eList, 1)); } else { results.offer(Authorization.ITEM_NOT_FOUND.getResponseMessage(packet, "Requested list not found.", true)); } // end of if (eList != null) else } // end of else } // end of else } } // JabberIqPrivacy
Fixed NPE when it tried to retrieve contact groups and the contact wasn't in any group git-svn-id: 4a0daf30c0bbd291b3bc5fe8f058bf11ee523347@857 7d282ba1-3ae6-0310-8f9b-c9008a0864d2
src/main/java/tigase/xmpp/impl/JabberIqPrivacy.java
Fixed NPE when it tried to retrieve contact groups and the contact wasn't in any group
<ide><path>rc/main/java/tigase/xmpp/impl/JabberIqPrivacy.java <ide> break; <ide> case group: <ide> String[] groups = Roster.getBuddyGroups(session, from); <del> for (String group: groups) { <del> if (type_matched = group.equals(value)) { <del> break; <del> } // end of if (group.equals(value)) <del> } // end of for (String group: groups) <add> if (groups != null) { <add> for (String group: groups) { <add> if (type_matched = group.equals(value)) { <add> break; <add> } // end of if (group.equals(value)) <add> } // end of for (String group: groups) <add> } <ide> break; <ide> case subscription: <ide> ITEM_SUBSCRIPTIONS subscr = ITEM_SUBSCRIPTIONS.valueOf(value);
JavaScript
apache-2.0
bb5d6bd3ba5295b7327271170f7236a416a6ac9c
0
lakhansamani/pouchdb,adamvert/pouchdb,Actonate/pouchdb,cdaringe/pouchdb,mattbailey/pouchdb,Actonate/pouchdb,Actonate/pouchdb,crissdev/pouchdb,jhs/pouchdb,crissdev/pouchdb,mainerror/pouchdb,mwksl/pouchdb,marcusandre/pouchdb,Charlotteis/pouchdb,slaskis/pouchdb,optikfluffel/pouchdb,Charlotteis/pouchdb,garrensmith/pouchdb,mainerror/pouchdb,elkingtonmcb/pouchdb,microlv/pouchdb,HospitalRun/pouchdb,johnofkorea/pouchdb,patrickgrey/pouchdb,janraasch/pouchdb,callahanchris/pouchdb,jhs/pouchdb,colinskow/pouchdb,asmiller/pouchdb,caolan/pouchdb,h4ki/pouchdb,microlv/pouchdb,mattbailey/pouchdb,mikeymckay/pouchdb,KlausTrainer/pouchdb,tyler-johnson/pouchdb,patrickgrey/pouchdb,slang800/pouchdb,shimaore/pouchdb,colinskow/pouchdb,nickcolley/pouchdb,cesine/pouchdb,greyhwndz/pouchdb,cdaringe/pouchdb,seigel/pouchdb,KlausTrainer/pouchdb,jhs/pouchdb,slang800/pouchdb,mikeymckay/pouchdb,yaronyg/pouchdb,tohagan/pouchdb,janraasch/pouchdb,tyler-johnson/pouchdb,lakhansamani/pouchdb,marcusandre/pouchdb,shimaore/pouchdb,cesarmarinhorj/pouchdb,Knowledge-OTP/pouchdb,daleharvey/pouchdb,p5150j/pouchdb,ramdhavepreetam/pouchdb,mattbailey/pouchdb,cshum/pouchdb,ntwcklng/pouchdb,lukevanhorn/pouchdb,greyhwndz/pouchdb,nicolasbrugneaux/pouchdb,nickcolley/pouchdb,nickcolley/pouchdb,cesarmarinhorj/pouchdb,nicolasbrugneaux/pouchdb,asmiller/pouchdb,mainerror/pouchdb,bbenezech/pouchdb,Knowledge-OTP/pouchdb,Knowledge-OTP/pouchdb,spMatti/pouchdb,elkingtonmcb/pouchdb,callahanchris/pouchdb,Dashed/pouchdb,lakhansamani/pouchdb,TechnicalPursuit/pouchdb,ntwcklng/pouchdb,evidenceprime/pouchdb,seigel/pouchdb,slang800/pouchdb,bbenezech/pouchdb,cesine/pouchdb,ramdhavepreetam/pouchdb,olafura/pouchdb,asmiller/pouchdb,h4ki/pouchdb,cshum/pouchdb,bbenezech/pouchdb,lukevanhorn/pouchdb,KlausTrainer/pouchdb,marcusandre/pouchdb,nicolasbrugneaux/pouchdb,daleharvey/pouchdb,slaskis/pouchdb,TechnicalPursuit/pouchdb,ntwcklng/pouchdb,janl/pouchdb,janraasch/pouchdb,mikeal/pouchdb,tohagan/pouchdb,slaskis/pouchdb,lukevanhorn/pouchdb,daleharvey/pouchdb,cshum/pouchdb,johnofkorea/pouchdb,maxogden/pouchdb,janl/pouchdb,optikfluffel/pouchdb,ramdhavepreetam/pouchdb,pouchdb/pouchdb,HospitalRun/pouchdb,adamvert/pouchdb,spMatti/pouchdb,mwksl/pouchdb,p5150j/pouchdb,tohagan/pouchdb,mikeymckay/pouchdb,callahanchris/pouchdb,Dashed/pouchdb,pouchdb/pouchdb,shimaore/pouchdb,elkingtonmcb/pouchdb,yaronyg/pouchdb,yaronyg/pouchdb,h4ki/pouchdb,colinskow/pouchdb,cdaringe/pouchdb,tyler-johnson/pouchdb,cesarmarinhorj/pouchdb,janl/pouchdb,crissdev/pouchdb,Charlotteis/pouchdb,pouchdb/pouchdb,spMatti/pouchdb,garrensmith/pouchdb,mwksl/pouchdb,optikfluffel/pouchdb,adamvert/pouchdb,HospitalRun/pouchdb,microlv/pouchdb,willholley/pouchdb,patrickgrey/pouchdb,p5150j/pouchdb,willholley/pouchdb,greyhwndz/pouchdb,johnofkorea/pouchdb,Dashed/pouchdb,seigel/pouchdb,TechnicalPursuit/pouchdb,willholley/pouchdb,garrensmith/pouchdb
// While most of the IDB behaviors match between implementations a // lot of the names still differ. This section tries to normalize the // different objects & methods. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB; window.IDBCursor = window.IDBCursor || window.webkitIDBCursor; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; window.IDBDatabaseException = window.IDBDatabaseException || window.webkitIDBDatabaseException; function sum(values) { return values.reduce(function(a, b) { return a + b; }, 0); } var IdbPouch = function(opts, callback) { // IndexedDB requires a versioned database structure, this is going to make // it hard to dynamically create object stores if we needed to for things // like views var POUCH_VERSION = 1; // The object stores created for each database // DOC_STORE stores the document meta data, its revision history and state var DOC_STORE = 'document-store'; // BY_SEQ_STORE stores a particular version of a document, keyed by its // sequence id var BY_SEQ_STORE = 'by-sequence'; // Where we store attachments var ATTACH_STORE = 'attach-store'; var api = {}; var req = indexedDB.open(opts.name, POUCH_VERSION); var name = opts.name; var update_seq = 0; var idb; req.onupgradeneeded = function(e) { var db = e.target.result; db.createObjectStore(DOC_STORE, {keyPath : 'id'}) .createIndex('seq', 'seq', {unique : true}); db.createObjectStore(BY_SEQ_STORE, {autoIncrement : true}); db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'}); }; req.onsuccess = function(e) { idb = e.target.result; idb.onversionchange = function() { idb.close(); }; // polyfill the new onupgradeneeded api for chrome if (idb.setVersion && Number(idb.version) !== POUCH_VERSION) { var versionReq = idb.setVersion(POUCH_VERSION); versionReq.onsuccess = function() { req.onupgradeneeded(e); req.onsuccess(e); }; return; } call(callback, null, api); }; req.onerror = function(e) { call(callback, {error: 'open', reason: e.toString()}); }; api.destroy = function(name, callback) { var req = indexedDB.deleteDatabase(name); req.onsuccess = function() { call(callback, null); }; req.onerror = function(e) { call(callback, {error: 'delete', reason: e.toString()}); }; }; api.valid = function() { return true; }; // Each database needs a unique id so that we can store the sequence // checkpoint without having other databases confuse itself, since // localstorage is per host this shouldnt conflict, if localstorage // gets wiped it isnt fatal, replications will just start from scratch api.id = function() { var id = localJSON.get(name + '_id', null); if (id === null) { id = Math.uuid(); localJSON.set(name + '_id', id); } return id; }; api.init = function(opts, callback) { }; api.bulkDocs = function(req, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } if (!req.docs) { return call(callback, Pouch.Errors.MISSING_BULK_DOCS); } var newEdits = 'new_edits' in opts ? opts.new_edits : true; // We dont want to modify the users variables in place, JSON is kinda // nasty for a deep clone though var docs = JSON.parse(JSON.stringify(req.docs)); // Parse and sort the docs var docInfos = docs.map(function(doc, i) { var newDoc = parseDoc(doc, newEdits); // We want to ensure the order of the processing and return of the docs, // so we give them a sequence number newDoc._bulk_seq = i; return newDoc; }); docInfos.sort(function(a, b) { if (a.error || b.error) { return -1; } return Pouch.collate(a.metadata.id, b.metadata.id); }); var results = []; var firstDoc; for (var i = 0; i < docInfos.length; i++) { if (docInfos[i].error) { results.push(docInfos[i]) } else { firstDoc = docInfos[i]; break; } } if (!firstDoc) { docInfos.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); docInfos.forEach(function(result) { delete result._bulk_seq; }); return call(callback, null, docInfos); } var keyRange = IDBKeyRange.bound( firstDoc.metadata.id, docInfos[docInfos.length-1].metadata.id, false, false); // This groups edits to the same document together var buckets = docInfos.reduce(function(acc, docInfo) { if (docInfo.metadata.id === acc[0][0].metadata.id) { acc[0].push(docInfo); } else { acc.unshift([docInfo]); } return acc; }, [[docInfos.shift()]]); //The reduce screws up the array ordering buckets.reverse(); buckets.forEach(function(bucket) { bucket.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); }); var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], IDBTransaction.READ_WRITE); txn.oncomplete = function(event) { var aresults = []; results.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); results.forEach(function(result) { delete result._bulk_seq; if (result.error) { aresults.push(result); } else { aresults.push({ ok: true, id: result.metadata.id, rev: result.metadata.rev, }); } if (result.error || /_local/.test(result.metadata.id)) { return; } var c = { id: result.metadata.id, seq: result.metadata.seq, changes: collectLeaves(result.metadata.rev_tree), doc: result.data }; api.changes.emit(c); }); call(callback, null, aresults); }; txn.onerror = function(event) { if (callback) { var code = event.target.errorCode; var message = Object.keys(IDBDatabaseException)[code-1].toLowerCase(); callback({ error : event.type, reason : message }); } }; txn.ontimeout = function(event) { if (callback) { var code = event.target.errorCode; var message = Object.keys(IDBDatabaseException)[code].toLowerCase(); callback({ error : event.type, reason : message }); } }; // right now fire and forget, needs cleaned function saveAttachment(digest, data) { txn.objectStore(ATTACH_STORE).put({digest: digest, body: data}); } function winningRev(pos, tree) { if (!tree[1].length) { return pos + '-' + tree[0]; } return winningRev(pos + 1, tree[1][0]); } var writeDoc = function(docInfo, callback) { for (var key in docInfo.data._attachments) { if (!docInfo.data._attachments[key].stub) { docInfo.data._attachments[key].stub = true; var data = docInfo.data._attachments[key].data; var digest = 'md5-' + Crypto.MD5(data); delete docInfo.data._attachments[key].data; docInfo.data._attachments[key].digest = digest; saveAttachment(digest, data); } } // The doc will need to refer back to its meta data document docInfo.data._id = docInfo.metadata.id; if (docInfo.metadata.deleted) { docInfo.data._deleted = true; } var dataReq = txn.objectStore(BY_SEQ_STORE).put(docInfo.data); dataReq.onsuccess = function(e) { docInfo.metadata.seq = e.target.result; // We probably shouldnt even store the winning rev, just figure it // out on read docInfo.metadata.rev = winningRev(docInfo.metadata.rev_tree[0].pos, docInfo.metadata.rev_tree[0].ids); var metaDataReq = txn.objectStore(DOC_STORE).put(docInfo.metadata); metaDataReq.onsuccess = function() { results.push(docInfo); call(callback); }; }; }; var makeErr = function(err, seq) { err._bulk_seq = seq; return err; }; var cursReq = txn.objectStore(DOC_STORE) .openCursor(keyRange, IDBCursor.NEXT); var update = function(cursor, oldDoc, docInfo, callback) { var mergedRevisions = Pouch.merge(oldDoc.rev_tree, docInfo.metadata.rev_tree[0], 1000); var inConflict = (oldDoc.deleted && docInfo.metadata.deleted) || (!oldDoc.deleted && newEdits && mergedRevisions.conflicts !== 'new_leaf'); if (inConflict) { results.push(makeErr(Pouch.Errors.REV_CONFLICT, docInfo._bulk_seq)); call(callback); return cursor['continue'](); } docInfo.metadata.rev_tree = mergedRevisions.tree; writeDoc(docInfo, function() { cursor['continue'](); call(callback); }); }; var insert = function(docInfo, callback) { if (docInfo.metadata.deleted) { results.push(Pouch.Errors.MISSING_DOC); return; } writeDoc(docInfo, function() { call(callback); }); }; // If we receive multiple items in bulkdocs with the same id, we process the // first but mark rest as conflicts until can think of a sensible reason // to not do so var markConflicts = function(docs) { for (var i = 1; i < docs.length; i++) { results.push(makeErr(Pouch.Errors.REV_CONFLICT, docs[i]._bulk_seq)); } }; cursReq.onsuccess = function(event) { var cursor = event.target.result; if (cursor && buckets.length) { var bucket = buckets.shift(); if (cursor.key === bucket[0].metadata.id) { update(cursor, cursor.value, bucket[0], function() { markConflicts(bucket); }); } else { insert(bucket[0], function() { markConflicts(bucket); }); } } else { // Cursor has exceeded the key range so the rest are inserts buckets.forEach(function(bucket) { insert(bucket[0], function() { markConflicts(bucket); }); }); } }; }; // First we look up the metadata in the ids database, then we fetch the // current revision(s) from the by sequence store api.get = function(id, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], IDBTransaction.READ); if (/\//.test(id) && !/^_local/.test(id) && !/^_design/.test(id)) { var docId = id.split('/')[0]; var attachId = id.split('/')[1]; txn.objectStore(DOC_STORE).get(docId).onsuccess = function(e) { var metadata = e.target.result; txn.objectStore(BY_SEQ_STORE).get(metadata.seq).onsuccess = function(e) { var digest = e.target.result._attachments[attachId].digest; txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function(e) { call(callback, null, atob(e.target.result.body)); }; }; } return; } txn.objectStore(DOC_STORE).get(id).onsuccess = function(e) { var metadata = e.target.result; if (!e.target.result || metadata.deleted) { return call(callback, Pouch.Errors.MISSING_DOC); } txn.objectStore(BY_SEQ_STORE).get(metadata.seq).onsuccess = function(e) { var doc = e.target.result; doc._id = metadata.id; doc._rev = metadata.rev; if (opts.revs) { var path = arrayFirst(rootToLeaf(metadata.rev_tree), function(arr) { return arr.ids.indexOf(metadata.rev.split('-')[1]) !== -1; }); path.ids.reverse(); doc._revisions = { start: (path.pos + path.ids.length) - 1, ids: path.ids }; } if (opts.revs_info) { doc._revs_info = metadata.rev_tree.reduce(function(prev, current) { return prev.concat(collectRevs(current)); }, []); } if (opts.attachments && doc._attachments) { var attachments = Object.keys(doc._attachments); var recv = 0; attachments.forEach(function(key) { api.get(doc._id + '/' + key, function(err, data) { doc._attachments[key].data = btoa(data); if (++recv === attachments.length) { callback(null, doc); } }); }); } else { callback(null, doc); } }; }; }; api.put = api.post = function(doc, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return api.bulkDocs({docs: [doc]}, opts, yankError(callback)); }; api.remove = function(doc, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var newDoc = JSON.parse(JSON.stringify(doc)); newDoc._deleted = true; return api.bulkDocs({docs: [newDoc]}, opts, yankError(callback)); }; api.allDocs = function(opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var start = 'startkey' in opts ? opts.startkey : false; var end = 'endkey' in opts ? opts.endkey : false; var descending = 'descending' in opts ? opts.descending : false; descending = descending ? IDBCursor.PREV : null; var keyRange = start && end ? IDBKeyRange.bound(start, end, false, false) : start ? IDBKeyRange.lowerBound(start, true) : end ? IDBKeyRange.upperBound(end) : false; var transaction = idb.transaction([DOC_STORE, BY_SEQ_STORE], IDBTransaction.READ); var oStore = transaction.objectStore(DOC_STORE); var oCursor = keyRange ? oStore.openCursor(keyRange, descending) : oStore.openCursor(null, descending); var results = []; oCursor.onsuccess = function(e) { if (!e.target.result) { return callback(null, { total_rows: results.length, rows: results }); } var cursor = e.target.result; function allDocsInner(metadata, data) { if (/_local/.test(metadata.id)) { return cursor['continue'](); } if (metadata.deleted !== true) { var doc = { id: metadata.id, key: metadata.id, value: {rev: metadata.rev} }; if (opts.include_docs) { doc.doc = data; doc.doc._rev = metadata.rev; if (opts.conflicts) { doc.doc._conflicts = collectConflicts(metadata.rev_tree); } } results.push(doc); } cursor['continue'](); } if (!opts.include_docs) { allDocsInner(cursor.value); } else { var index = transaction.objectStore(BY_SEQ_STORE); index.get(cursor.value.seq).onsuccess = function(event) { allDocsInner(cursor.value, event.target.result); }; } } }; // Looping through all the documents in the database is a terrible idea // easiest to implement though, should probably keep a counter api.info = function(callback) { var count = 0; idb.transaction([DOC_STORE], IDBTransaction.READ) .objectStore(DOC_STORE).openCursor().onsuccess = function(e) { var cursor = e.target.result; if (!cursor) { return callback(null, { db_name: name, doc_count: count, update_seq: update_seq }); } if (cursor.value.deleted !== true) { count++; } cursor['continue'](); }; }; api.putAttachment = function(id, rev, doc, type, callback) { var docId = id.split('/')[0]; var attachId = id.split('/')[1]; api.get(docId, function(err, obj) { obj._attachments || (obj._attachments = {}); obj._attachments[attachId] = { content_type: type, data: btoa(doc) } api.put(obj, callback); }); }; api.revsDiff = function(req, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var ids = Object.keys(req); var count = 0; var missing = {}; function readDoc(err, doc, id) { req[id].map(function(revId) { if (!doc || doc._revs_info.every(function(x) { return x.rev !== revId; })) { if (!missing[id]) { missing[id] = {missing: []}; } missing[id].missing.push(revId); } }); if (++count === ids.length) { return call(callback, null, missing); } } ids.map(function(id) { api.get(id, {revs_info: true}, function(err, doc) { readDoc(err, doc, id); }); }); }; api.changes = function(opts, callback) { if (opts instanceof Function) { opts = {complete: opts}; } if (callback) { opts.complete = callback; } if (!opts.seq) { opts.seq = 0; } var descending = 'descending' in opts ? opts.descending : false; descending = descending ? IDBCursor.PREV : null; var results = []; var id = Math.uuid(); var txn; if (opts.filter && typeof opts.filter === 'string') { var filterName = opts.filter.split('/'); api.get('_design/' + filterName[0], function(err, ddoc) { var filter = eval('(function() { return ' + ddoc.filters[filterName[1]] + ' })()'); opts.filter = filter; txn = idb.transaction([DOC_STORE, BY_SEQ_STORE]); var req = txn.objectStore(BY_SEQ_STORE) .openCursor(IDBKeyRange.lowerBound(opts.seq), descending); req.onsuccess = onsuccess; req.onerror = onerror; }); } else { txn = idb.transaction([DOC_STORE, BY_SEQ_STORE]); var req = txn.objectStore(BY_SEQ_STORE) .openCursor(IDBKeyRange.lowerBound(opts.seq), descending); req.onsuccess = onsuccess; req.onerror = onerror; } function onsuccess(event) { if (!event.target.result) { if (opts.continuous) { api.changes.addListener(id, opts); } results.map(function(c) { if (opts.filter && !opts.filter.apply(this, [c.doc])) { return; } if (!opts.include_docs) { delete c.doc; } call(opts.onChange, c); }); return call(opts.complete, null, {results: results}); } var cursor = event.target.result; var index = txn.objectStore(DOC_STORE); index.get(cursor.value._id).onsuccess = function(event) { var doc = event.target.result; if (/_local/.test(doc.id)) { return cursor['continue'](); } var c = { id: doc.id, seq: cursor.key, changes: collectLeaves(doc.rev_tree), doc: cursor.value, }; c.doc._rev = doc.rev; if (doc.deleted) { c.deleted = true; } if (opts.include_docs) { c.doc._rev = c.changes[0].rev; if (opts.conflicts) { c.doc._conflicts = collectConflicts(doc.rev_tree); } } // Dedupe the changes feed results = results.filter(function(doc) { return doc.id !== c.id; }); results.push(c); cursor['continue'](); }; }; function onerror(error) { // Cursor is out of range // NOTE: What should we do with a sequence that is too high? if (opts.continuous) { db.changes.addListener(id, opts); } call(opts.complete); }; if (opts.continuous) { // Possible race condition when the user cancels a continous changes feed // before the current changes are finished (therefore before the listener // is added return { cancel: function() { delete api.changes.listeners[id]; } } } }; api.changes.listeners = {}; api.changes.emit = function() { var a = arguments; for (var i in api.changes.listeners) { var opts = api.changes.listeners[i]; if (opts.filter && !opts.filter.apply(this, [a[0].doc])) { return; } opts.onChange.apply(opts.onChange, a); } }; api.changes.addListener = function(id, opts, callback) { api.changes.listeners[id] = opts; }; api.replicate = {}; api.replicate.from = function(url, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return Pouch.replicate(url, api, opts, callback); }; api.replicate.to = function(dbName, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return Pouch.replicate(api, dbName, opts, callback); }; api.query = function(fun, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } if (callback) { opts.complete = callback; } if (typeof fun === 'string') { var parts = fun.split('/'); api.get('_design/' + parts[0], function(err, doc) { if (err) { call(callback, err); } eval('var map = ' + doc.views[parts[1]].map); // TODO: reduce may not be defined, or may be predefined eval('var reduce = ' + doc.views[parts[1]].reduce); viewQuery({map: map, reduce: reduce}, idb, opts); }); } else { viewQuery(fun, idb, opts); } } // Wrapper for functions that call the bulkdocs api with a single doc, // if the first result is an error, return an error var yankError = function(callback) { return function(err, results) { if (err || results[0].error) { call(callback, err || results[0]); } else { call(callback, null, results[0]); } }; }; var viewQuery = function (fun, idb, options) { var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE], IDBTransaction.READ); var objectStore = txn.objectStore(DOC_STORE); var request = objectStore.openCursor(); var mapContext = {}; var results = []; var current; emit = function(key, val) { results.push({ id: current._id, key: key, value: val }); } request.onsuccess = function (e) { var cursor = e.target.result; if (!cursor) { if (options.complete) { results.sort(function(a, b) { return Pouch.collate(a.key, b.key); }); if (options.descending) { results.reverse(); } if (options.reduce !== false) { var groups = []; results.forEach(function(e) { var last = groups[groups.length-1] || null; if (last && Pouch.collate(last.key[0][0], e.key) === 0) { last.key.push([e.key, e.id]); last.value.push(e.value); return; } groups.push({ key: [ [e.key,e.id] ], value: [ e.value ]}); }); groups.forEach(function(e) { e.value = fun.reduce(e.key, e.value) || null; e.key = e.key[0][0]; }); options.complete(null, {rows: groups}); } else { options.complete(null, {rows: results}); } } } else { var nreq = txn .objectStore(BY_SEQ_STORE).get(e.target.result.value.seq) .onsuccess = function(e) { current = e.target.result; if (options.complete) { fun.map.apply(mapContext, [current]); } cursor['continue'](); }; } } request.onerror = function (error) { if (options.error) { options.error(error); } } } return api; }; IdbPouch.valid = function() { return true; }; IdbPouch.destroy = function(name, callback) { var req = indexedDB.deleteDatabase(name); req.onsuccess = function() { call(callback, null); }; req.onerror = function(e) { call(callback, {error: 'delete', reason: e.toString()}); }; }; Pouch.adapter('idb', IdbPouch);
src/adapters/pouch.idb.js
// While most of the IDB behaviors match between implementations a // lot of the names still differ. This section tries to normalize the // different objects & methods. window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB; window.IDBCursor = window.IDBCursor || window.webkitIDBCursor; window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange; window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; window.IDBDatabaseException = window.IDBDatabaseException || window.webkitIDBDatabaseException; function sum(values) { return values.reduce(function(a, b) { return a + b; }, 0); } var IdbPouch = function(opts, callback) { // IndexedDB requires a versioned database structure, this is going to make // it hard to dynamically create object stores if we needed to for things // like views var POUCH_VERSION = 1; // The object stores created for each database // DOC_STORE stores the document meta data, its revision history and state var DOC_STORE = 'document-store'; // BY_SEQ_STORE stores a particular version of a document, keyed by its // sequence id var BY_SEQ_STORE = 'by-sequence'; // Where we store attachments var ATTACH_STORE = 'attach-store'; var api = {}; var req = indexedDB.open(opts.name, POUCH_VERSION); var name = opts.name; var update_seq = 0; var idb; req.onupgradeneeded = function(e) { var db = e.target.result; db.createObjectStore(DOC_STORE, {keyPath : 'id'}) .createIndex('seq', 'seq', {unique : true}); db.createObjectStore(BY_SEQ_STORE, {autoIncrement : true}); db.createObjectStore(ATTACH_STORE, {keyPath: 'digest'}); }; req.onsuccess = function(e) { idb = e.target.result; idb.onversionchange = function() { idb.close(); }; // polyfill the new onupgradeneeded api for chrome if (idb.setVersion && Number(idb.version) !== POUCH_VERSION) { var versionReq = idb.setVersion(POUCH_VERSION); versionReq.onsuccess = function() { req.onupgradeneeded(e); req.onsuccess(e); }; return; } call(callback, null, api); }; req.onerror = function(e) { call(callback, {error: 'open', reason: e.toString()}); }; api.destroy = function(name, callback) { var req = indexedDB.deleteDatabase(name); req.onsuccess = function() { call(callback, null); }; req.onerror = function(e) { call(callback, {error: 'delete', reason: e.toString()}); }; }; api.valid = function() { return true; }; // Each database needs a unique id so that we can store the sequence // checkpoint without having other databases confuse itself, since // localstorage is per host this shouldnt conflict, if localstorage // gets wiped it isnt fatal, replications will just start from scratch api.id = function() { var id = localJSON.get(name + '_id', null); if (id === null) { id = Math.uuid(); localJSON.set(name + '_id', id); } return id; }; api.init = function(opts, callback) { }; api.bulkDocs = function(req, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } if (!req.docs) { return call(callback, Pouch.Errors.MISSING_BULK_DOCS); } var newEdits = 'new_edits' in opts ? opts.new_edits : true; // We dont want to modify the users variables in place, JSON is kinda // nasty for a deep clone though var docs = JSON.parse(JSON.stringify(req.docs)); // Parse and sort the docs var docInfos = docs.map(function(doc, i) { var newDoc = parseDoc(doc, newEdits); // We want to ensure the order of the processing and return of the docs, // so we give them a sequence number newDoc._bulk_seq = i; return newDoc; }); docInfos.sort(function(a, b) { if (a.error || b.error) { return -1; } return Pouch.collate(a.metadata.id, b.metadata.id); }); var results = []; var firstDoc; for (var i = 0; i < docInfos.length; i++) { if (docInfos[i].error) { results.push(docInfos[i]) } else { firstDoc = docInfos[i]; break; } } if (!firstDoc) { docInfos.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); docInfos.forEach(function(result) { delete result._bulk_seq; }); return call(callback, null, docInfos); } var keyRange = IDBKeyRange.bound( firstDoc.metadata.id, docInfos[docInfos.length-1].metadata.id, false, false); // This groups edits to the same document together var buckets = docInfos.reduce(function(acc, docInfo) { if (docInfo.metadata.id === acc[0][0].metadata.id) { acc[0].push(docInfo); } else { acc.unshift([docInfo]); } return acc; }, [[docInfos.shift()]]); //The reduce screws up the array ordering buckets.reverse(); buckets.forEach(function(bucket) { bucket.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); }); var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], IDBTransaction.READ_WRITE); txn.oncomplete = function(event) { var aresults = []; results.sort(function(a, b) { return a._bulk_seq - b._bulk_seq; }); results.forEach(function(result) { delete result._bulk_seq; if (result.error) { aresults.push(result); } else { aresults.push({ ok: true, id: result.metadata.id, rev: result.metadata.rev, }); } if (result.error || /_local/.test(result.metadata.id)) { return; } var c = { id: result.metadata.id, seq: result.metadata.seq, changes: collectLeaves(result.metadata.rev_tree), doc: result.data }; api.changes.emit(c); }); call(callback, null, aresults); }; txn.onerror = function(event) { if (callback) { var code = event.target.errorCode; var message = Object.keys(IDBDatabaseException)[code-1].toLowerCase(); callback({ error : event.type, reason : message }); } }; txn.ontimeout = function(event) { if (callback) { var code = event.target.errorCode; var message = Object.keys(IDBDatabaseException)[code].toLowerCase(); callback({ error : event.type, reason : message }); } }; // right now fire and forget, needs cleaned function saveAttachment(digest, data) { txn.objectStore(ATTACH_STORE).put({digest: digest, body: data}); } function winningRev(pos, tree) { if (!tree[1].length) { return pos + '-' + tree[0]; } return winningRev(pos + 1, tree[1][0]); } var writeDoc = function(docInfo, callback) { for (var key in docInfo.data._attachments) { if (!docInfo.data._attachments[key].stub) { docInfo.data._attachments[key].stub = true; var data = docInfo.data._attachments[key].data; var digest = 'md5-' + Crypto.MD5(data); delete docInfo.data._attachments[key].data; docInfo.data._attachments[key].digest = digest; saveAttachment(digest, data); } } // The doc will need to refer back to its meta data document docInfo.data._id = docInfo.metadata.id; if (docInfo.metadata.deleted) { docInfo.data._deleted = true; } var dataReq = txn.objectStore(BY_SEQ_STORE).put(docInfo.data); dataReq.onsuccess = function(e) { docInfo.metadata.seq = e.target.result; // We probably shouldnt even store the winning rev, just figure it // out on read docInfo.metadata.rev = winningRev(docInfo.metadata.rev_tree[0].pos, docInfo.metadata.rev_tree[0].ids); var metaDataReq = txn.objectStore(DOC_STORE).put(docInfo.metadata); metaDataReq.onsuccess = function() { results.push(docInfo); call(callback); }; }; }; var makeErr = function(err, seq) { err._bulk_seq = seq; return err; }; var cursReq = txn.objectStore(DOC_STORE) .openCursor(keyRange, IDBCursor.NEXT); var update = function(cursor, oldDoc, docInfo, callback) { var mergedRevisions = Pouch.merge(oldDoc.rev_tree, docInfo.metadata.rev_tree[0], 1000); var inConflict = (oldDoc.deleted && docInfo.metadata.deleted) || (!oldDoc.deleted && newEdits && mergedRevisions.conflicts !== 'new_leaf'); if (inConflict) { results.push(makeErr(Pouch.Errors.REV_CONFLICT, docInfo._bulk_seq)); call(callback); return cursor['continue'](); } docInfo.metadata.rev_tree = mergedRevisions.tree; writeDoc(docInfo, function() { cursor['continue'](); call(callback); }); }; var insert = function(docInfo, callback) { if (docInfo.metadata.deleted) { results.push(Pouch.Errors.MISSING_DOC); return; } writeDoc(docInfo, function() { call(callback); }); }; // If we receive multiple items in bulkdocs with the same id, we process the // first but mark rest as conflicts until can think of a sensible reason // to not do so var markConflicts = function(docs) { for (var i = 1; i < docs.length; i++) { results.push(makeErr(Pouch.Errors.REV_CONFLICT, docs[i]._bulk_seq)); } }; cursReq.onsuccess = function(event) { var cursor = event.target.result; if (cursor && buckets.length) { var bucket = buckets.shift(); if (cursor.key === bucket[0].metadata.id) { update(cursor, cursor.value, bucket[0], function() { markConflicts(bucket); }); } else { insert(bucket[0], function() { markConflicts(bucket); }); } } else { // Cursor has exceeded the key range so the rest are inserts buckets.forEach(function(bucket) { insert(bucket[0], function() { markConflicts(bucket); }); }); } }; }; // First we look up the metadata in the ids database, then we fetch the // current revision(s) from the by sequence store api.get = function(id, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE, ATTACH_STORE], IDBTransaction.READ); if (/\//.test(id) && !/^_local/.test(id) && !/^_design/.test(id)) { var docId = id.split('/')[0]; var attachId = id.split('/')[1]; txn.objectStore(DOC_STORE).get(docId).onsuccess = function(e) { var metadata = e.target.result; txn.objectStore(BY_SEQ_STORE).get(metadata.seq).onsuccess = function(e) { var digest = e.target.result._attachments[attachId].digest; txn.objectStore(ATTACH_STORE).get(digest).onsuccess = function(e) { call(callback, null, atob(e.target.result.body)); }; }; } return; } txn.objectStore(DOC_STORE).get(id).onsuccess = function(e) { var metadata = e.target.result; if (!e.target.result || metadata.deleted) { return call(callback, Pouch.Errors.MISSING_DOC); } txn.objectStore(BY_SEQ_STORE).get(metadata.seq).onsuccess = function(e) { var doc = e.target.result; doc._id = metadata.id; doc._rev = metadata.rev; if (opts.revs) { var path = arrayFirst(rootToLeaf(metadata.rev_tree), function(arr) { return arr.ids.indexOf(metadata.rev.split('-')[1]) !== -1; }); path.ids.reverse(); doc._revisions = { start: (path.pos + path.ids.length) - 1, ids: path.ids }; } if (opts.revs_info) { doc._revs_info = metadata.rev_tree.reduce(function(prev, current) { return prev.concat(collectRevs(current)); }, []); } if (opts.attachments && doc._attachments) { var attachments = Object.keys(doc._attachments); var recv = 0; attachments.forEach(function(key) { api.get(doc._id + '/' + key, function(err, data) { doc._attachments[key].data = btoa(data); if (++recv === attachments.length) { callback(null, doc); } }); }); } else { callback(null, doc); } }; }; }; api.put = api.post = function(doc, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return api.bulkDocs({docs: [doc]}, opts, yankError(callback)); }; api.remove = function(doc, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var newDoc = JSON.parse(JSON.stringify(doc)); newDoc._deleted = true; return api.bulkDocs({docs: [newDoc]}, opts, yankError(callback)); }; api.allDocs = function(opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var start = 'startkey' in opts ? opts.startkey : false; var end = 'endkey' in opts ? opts.endkey : false; var descending = 'descending' in opts ? opts.descending : false; descending = descending ? IDBCursor.PREV : null; var keyRange = start && end ? IDBKeyRange.bound(start, end, false, false) : start ? IDBKeyRange.lowerBound(start, true) : end ? IDBKeyRange.upperBound(end) : false; var transaction = idb.transaction([DOC_STORE, BY_SEQ_STORE], IDBTransaction.READ); var oStore = transaction.objectStore(DOC_STORE); var oCursor = keyRange ? oStore.openCursor(keyRange, descending) : oStore.openCursor(null, descending); var results = []; oCursor.onsuccess = function(e) { if (!e.target.result) { return callback(null, { total_rows: results.length, rows: results }); } var cursor = e.target.result; function allDocsInner(metadata, data) { if (/_local/.test(metadata.id)) { return cursor['continue'](); } if (metadata.deleted !== true) { var doc = { id: metadata.id, key: metadata.id, value: {rev: metadata.rev} }; if (opts.include_docs) { doc.doc = data; doc.doc._rev = metadata.rev; if (opts.conflicts) { doc.doc._conflicts = collectConflicts(metadata.rev_tree); } } results.push(doc); } cursor['continue'](); } if (!opts.include_docs) { allDocsInner(cursor.value); } else { var index = transaction.objectStore(BY_SEQ_STORE); index.get(cursor.value.seq).onsuccess = function(event) { allDocsInner(cursor.value, event.target.result); }; } } }; // Looping through all the documents in the database is a terrible idea // easiest to implement though, should probably keep a counter api.info = function(callback) { var count = 0; idb.transaction([DOC_STORE], IDBTransaction.READ) .objectStore(DOC_STORE).openCursor().onsuccess = function(e) { var cursor = e.target.result; if (!cursor) { return callback(null, { db_name: name, doc_count: count, update_seq: update_seq }); } if (cursor.value.deleted !== true) { count++; } cursor['continue'](); }; }; api.putAttachment = function(id, rev, doc, type, callback) { var docId = id.split('/')[0]; var attachId = id.split('/')[1]; api.get(docId, function(err, obj) { obj._attachments[attachId] = { content_type: type, data: btoa(doc) } api.put(obj, callback); }); }; api.revsDiff = function(req, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } var ids = Object.keys(req); var count = 0; var missing = {}; function readDoc(err, doc, id) { req[id].map(function(revId) { if (!doc || doc._revs_info.every(function(x) { return x.rev !== revId; })) { if (!missing[id]) { missing[id] = {missing: []}; } missing[id].missing.push(revId); } }); if (++count === ids.length) { return call(callback, null, missing); } } ids.map(function(id) { api.get(id, {revs_info: true}, function(err, doc) { readDoc(err, doc, id); }); }); }; api.changes = function(opts, callback) { if (opts instanceof Function) { opts = {complete: opts}; } if (callback) { opts.complete = callback; } if (!opts.seq) { opts.seq = 0; } var descending = 'descending' in opts ? opts.descending : false; descending = descending ? IDBCursor.PREV : null; var results = []; var id = Math.uuid(); var txn; if (opts.filter && typeof opts.filter === 'string') { var filterName = opts.filter.split('/'); api.get('_design/' + filterName[0], function(err, ddoc) { var filter = eval('(function() { return ' + ddoc.filters[filterName[1]] + ' })()'); opts.filter = filter; txn = idb.transaction([DOC_STORE, BY_SEQ_STORE]); var req = txn.objectStore(BY_SEQ_STORE) .openCursor(IDBKeyRange.lowerBound(opts.seq), descending); req.onsuccess = onsuccess; req.onerror = onerror; }); } else { txn = idb.transaction([DOC_STORE, BY_SEQ_STORE]); var req = txn.objectStore(BY_SEQ_STORE) .openCursor(IDBKeyRange.lowerBound(opts.seq), descending); req.onsuccess = onsuccess; req.onerror = onerror; } function onsuccess(event) { if (!event.target.result) { if (opts.continuous) { api.changes.addListener(id, opts); } results.map(function(c) { if (opts.filter && !opts.filter.apply(this, [c.doc])) { return; } if (!opts.include_docs) { delete c.doc; } call(opts.onChange, c); }); return call(opts.complete, null, {results: results}); } var cursor = event.target.result; var index = txn.objectStore(DOC_STORE); index.get(cursor.value._id).onsuccess = function(event) { var doc = event.target.result; if (/_local/.test(doc.id)) { return cursor['continue'](); } var c = { id: doc.id, seq: cursor.key, changes: collectLeaves(doc.rev_tree), doc: cursor.value, }; c.doc._rev = doc.rev; if (doc.deleted) { c.deleted = true; } if (opts.include_docs) { c.doc._rev = c.changes[0].rev; if (opts.conflicts) { c.doc._conflicts = collectConflicts(doc.rev_tree); } } // Dedupe the changes feed results = results.filter(function(doc) { return doc.id !== c.id; }); results.push(c); cursor['continue'](); }; }; function onerror(error) { // Cursor is out of range // NOTE: What should we do with a sequence that is too high? if (opts.continuous) { db.changes.addListener(id, opts); } call(opts.complete); }; if (opts.continuous) { // Possible race condition when the user cancels a continous changes feed // before the current changes are finished (therefore before the listener // is added return { cancel: function() { delete api.changes.listeners[id]; } } } }; api.changes.listeners = {}; api.changes.emit = function() { var a = arguments; for (var i in api.changes.listeners) { var opts = api.changes.listeners[i]; if (opts.filter && !opts.filter.apply(this, [a[0].doc])) { return; } opts.onChange.apply(opts.onChange, a); } }; api.changes.addListener = function(id, opts, callback) { api.changes.listeners[id] = opts; }; api.replicate = {}; api.replicate.from = function(url, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return Pouch.replicate(url, api, opts, callback); }; api.replicate.to = function(dbName, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } return Pouch.replicate(api, dbName, opts, callback); }; api.query = function(fun, opts, callback) { if (opts instanceof Function) { callback = opts; opts = {}; } if (callback) { opts.complete = callback; } if (typeof fun === 'string') { var parts = fun.split('/'); api.get('_design/' + parts[0], function(err, doc) { if (err) { call(callback, err); } eval('var map = ' + doc.views[parts[1]].map); // TODO: reduce may not be defined, or may be predefined eval('var reduce = ' + doc.views[parts[1]].reduce); viewQuery({map: map, reduce: reduce}, idb, opts); }); } else { viewQuery(fun, idb, opts); } } // Wrapper for functions that call the bulkdocs api with a single doc, // if the first result is an error, return an error var yankError = function(callback) { return function(err, results) { if (err || results[0].error) { call(callback, err || results[0]); } else { call(callback, null, results[0]); } }; }; var viewQuery = function (fun, idb, options) { var txn = idb.transaction([DOC_STORE, BY_SEQ_STORE], IDBTransaction.READ); var objectStore = txn.objectStore(DOC_STORE); var request = objectStore.openCursor(); var mapContext = {}; var results = []; var current; emit = function(key, val) { results.push({ id: current._id, key: key, value: val }); } request.onsuccess = function (e) { var cursor = e.target.result; if (!cursor) { if (options.complete) { results.sort(function(a, b) { return Pouch.collate(a.key, b.key); }); if (options.descending) { results.reverse(); } if (options.reduce !== false) { var groups = []; results.forEach(function(e) { var last = groups[groups.length-1] || null; if (last && Pouch.collate(last.key[0][0], e.key) === 0) { last.key.push([e.key, e.id]); last.value.push(e.value); return; } groups.push({ key: [ [e.key,e.id] ], value: [ e.value ]}); }); groups.forEach(function(e) { e.value = fun.reduce(e.key, e.value) || null; e.key = e.key[0][0]; }); options.complete(null, {rows: groups}); } else { options.complete(null, {rows: results}); } } } else { var nreq = txn .objectStore(BY_SEQ_STORE).get(e.target.result.value.seq) .onsuccess = function(e) { current = e.target.result; if (options.complete) { fun.map.apply(mapContext, [current]); } cursor['continue'](); }; } } request.onerror = function (error) { if (options.error) { options.error(error); } } } return api; }; IdbPouch.valid = function() { return true; }; IdbPouch.destroy = function(name, callback) { var req = indexedDB.deleteDatabase(name); req.onsuccess = function() { call(callback, null); }; req.onerror = function(e) { call(callback, {error: 'delete', reason: e.toString()}); }; }; Pouch.adapter('idb', IdbPouch);
Fix putAttachment on a doc without attachments
src/adapters/pouch.idb.js
Fix putAttachment on a doc without attachments
<ide><path>rc/adapters/pouch.idb.js <ide> var docId = id.split('/')[0]; <ide> var attachId = id.split('/')[1]; <ide> api.get(docId, function(err, obj) { <add> obj._attachments || (obj._attachments = {}); <ide> obj._attachments[attachId] = { <ide> content_type: type, <ide> data: btoa(doc)
Java
apache-2.0
84ef23f404bc5b09935d258c5d89925668737f9e
0
apache/syncope,apache/syncope,apache/syncope,ilgrosso/syncope,apache/syncope,ilgrosso/syncope,ilgrosso/syncope,ilgrosso/syncope
/* * 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.syncope.client.console.wizards.resources; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.syncope.client.console.init.ClassPathScanImplementationLookup; import org.apache.syncope.client.console.wicket.markup.html.form.AjaxTextFieldPanel; import org.apache.syncope.common.lib.to.AnyTypeClassTO; import org.apache.syncope.common.lib.to.ItemTO; import org.apache.syncope.common.lib.to.SAML2IdPTO; import org.apache.syncope.common.lib.types.AnyTypeKind; import org.apache.syncope.common.lib.types.MappingPurpose; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.util.ListModel; public class SAML2IdPMappingPanel extends AbstractMappingPanel { private static final long serialVersionUID = 2248901624411541853L; public SAML2IdPMappingPanel( final String id, final SAML2IdPTO idpTO, final ItemTransformersTogglePanel mapItemTransformers, final JEXLTransformersTogglePanel jexlTransformers) { super(id, mapItemTransformers, jexlTransformers, new ListModel<ItemTO>(idpTO.getItems()), true, true, MappingPurpose.NONE); setOutputMarkupId(true); } @Override protected void onBeforeRender() { super.onBeforeRender(); purposeLabel.setVisible(false); } @Override protected IModel<List<String>> getExtAttrNames() { return Model.ofList(Collections.<String>singletonList("NameID")); } @Override protected void setAttrNames(final AjaxTextFieldPanel toBeUpdated) { toBeUpdated.setRequired(true); toBeUpdated.setEnabled(true); List<String> choices = new ArrayList<>(ClassPathScanImplementationLookup.USER_FIELD_NAMES); for (AnyTypeClassTO anyTypeClassTO : anyTypeClassRestClient.list( anyTypeRestClient.read(AnyTypeKind.USER.name()).getClasses())) { choices.addAll(anyTypeClassTO.getPlainSchemas()); choices.addAll(anyTypeClassTO.getDerSchemas()); choices.addAll(anyTypeClassTO.getVirSchemas()); } Collections.sort(choices); toBeUpdated.setChoices(choices); } }
ext/saml2sp/client-console/src/main/java/org/apache/syncope/client/console/wizards/resources/SAML2IdPMappingPanel.java
/* * 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.syncope.client.console.wizards.resources; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.syncope.client.console.init.ClassPathScanImplementationLookup; import org.apache.syncope.client.console.wicket.markup.html.form.AjaxTextFieldPanel; import org.apache.syncope.client.console.wizards.resources.AbstractMappingPanel; import org.apache.syncope.client.console.wizards.resources.JEXLTransformersTogglePanel; import org.apache.syncope.client.console.wizards.resources.ItemTransformersTogglePanel; import org.apache.syncope.common.lib.to.AnyTypeClassTO; import org.apache.syncope.common.lib.to.ItemTO; import org.apache.syncope.common.lib.to.SAML2IdPTO; import org.apache.syncope.common.lib.types.AnyTypeKind; import org.apache.syncope.common.lib.types.MappingPurpose; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.util.ListModel; public class SAML2IdPMappingPanel extends AbstractMappingPanel { private static final long serialVersionUID = 2248901624411541853L; public SAML2IdPMappingPanel( final String id, final SAML2IdPTO idpTO, final ItemTransformersTogglePanel mapItemTransformers, final JEXLTransformersTogglePanel jexlTransformers) { super(id, mapItemTransformers, jexlTransformers, new ListModel<ItemTO>(idpTO.getItems()), true, true, MappingPurpose.NONE); setOutputMarkupId(true); } @Override protected void onBeforeRender() { super.onBeforeRender(); purposeLabel.setVisible(false); } @Override protected IModel<List<String>> getExtAttrNames() { return Model.ofList(Collections.<String>singletonList("NameID")); } @Override protected void setAttrNames(final AjaxTextFieldPanel toBeUpdated) { toBeUpdated.setRequired(true); toBeUpdated.setEnabled(true); List<String> choices = new ArrayList<>(ClassPathScanImplementationLookup.USER_FIELD_NAMES); for (AnyTypeClassTO anyTypeClassTO : anyTypeClassRestClient.list( anyTypeRestClient.read(AnyTypeKind.USER.name()).getClasses())) { choices.addAll(anyTypeClassTO.getPlainSchemas()); choices.addAll(anyTypeClassTO.getDerSchemas()); choices.addAll(anyTypeClassTO.getVirSchemas()); } Collections.sort(choices); toBeUpdated.setChoices(choices); } }
[SYNCOPE-1410] Fix redundant import
ext/saml2sp/client-console/src/main/java/org/apache/syncope/client/console/wizards/resources/SAML2IdPMappingPanel.java
[SYNCOPE-1410] Fix redundant import
<ide><path>xt/saml2sp/client-console/src/main/java/org/apache/syncope/client/console/wizards/resources/SAML2IdPMappingPanel.java <ide> import java.util.List; <ide> import org.apache.syncope.client.console.init.ClassPathScanImplementationLookup; <ide> import org.apache.syncope.client.console.wicket.markup.html.form.AjaxTextFieldPanel; <del>import org.apache.syncope.client.console.wizards.resources.AbstractMappingPanel; <del>import org.apache.syncope.client.console.wizards.resources.JEXLTransformersTogglePanel; <del>import org.apache.syncope.client.console.wizards.resources.ItemTransformersTogglePanel; <ide> import org.apache.syncope.common.lib.to.AnyTypeClassTO; <ide> import org.apache.syncope.common.lib.to.ItemTO; <ide> import org.apache.syncope.common.lib.to.SAML2IdPTO;
Java
mit
89bdc592cff324588b26a15a96b6c9f9a5a3a6f1
0
balazspete/multi-hop-train-journey-booking
package communication.protocols; import java.util.Iterator; import java.util.Set; import communication.messages.HelloReplyMessage; import communication.messages.HelloType; import communication.messages.Message; import data.system.NodeInfo; public class HelloProtocol implements Protocol { private Set<NodeInfo> nodes; public HelloProtocol(Set<NodeInfo> nodes) { this.nodes = nodes; } @Override public String getAcceptedMessageType() { return "HelloMessage"; } @Override public Message processMessage(Message message) { NodeInfo node = message.getSender(); HelloReplyMessage reply = new HelloReplyMessage(); HelloType type = (HelloType) message.getContents(); if (type == HelloType.HI) { if (!containsNode(node)) { nodes.add(node); } reply.setContents(HelloType.HI); } else { if (!containsNode(node)) { nodes.remove(node); } reply.setContents(HelloType.BYE); } reply.setHelloer(message.getSender()); return reply; } @Override public boolean hasReply() { return true; } private boolean containsNode(NodeInfo node) { Iterator<NodeInfo> _nodes = nodes.iterator(); while (_nodes.hasNext()) { if (_nodes.next().equals(node)) { return true; } } return false; } }
src/communication/protocols/HelloProtocol.java
package communication.protocols; import java.util.Set; import communication.messages.HelloReplyMessage; import communication.messages.HelloType; import communication.messages.Message; import data.system.NodeInfo; public class HelloProtocol implements Protocol { private Set<NodeInfo> nodes; public HelloProtocol(Set<NodeInfo> nodes) { this.nodes = nodes; } @Override public String getAcceptedMessageType() { return "HelloMessage"; } @Override public Message processMessage(Message message) { NodeInfo node = message.getSender(); HelloReplyMessage reply = new HelloReplyMessage(); HelloType type = (HelloType) message.getContents(); if (type == HelloType.HI) { if (!nodes.contains(node)) { nodes.add(node); } reply.setContents(HelloType.HI); } else { if (!nodes.contains(node)) { nodes.remove(node); } reply.setContents(HelloType.BYE); } reply.setHelloer(message.getSender()); return reply; } @Override public boolean hasReply() { return true; } }
Fix NodeInfo filtering in HelloProtocol
src/communication/protocols/HelloProtocol.java
Fix NodeInfo filtering in HelloProtocol
<ide><path>rc/communication/protocols/HelloProtocol.java <ide> package communication.protocols; <ide> <add>import java.util.Iterator; <ide> import java.util.Set; <ide> <ide> import communication.messages.HelloReplyMessage; <ide> <ide> HelloType type = (HelloType) message.getContents(); <ide> if (type == HelloType.HI) { <del> if (!nodes.contains(node)) { <add> if (!containsNode(node)) { <ide> nodes.add(node); <ide> } <ide> <ide> reply.setContents(HelloType.HI); <ide> } else { <del> if (!nodes.contains(node)) { <add> if (!containsNode(node)) { <ide> nodes.remove(node); <ide> } <ide> <ide> public boolean hasReply() { <ide> return true; <ide> } <add> <add> private boolean containsNode(NodeInfo node) { <add> Iterator<NodeInfo> _nodes = nodes.iterator(); <add> while (_nodes.hasNext()) { <add> if (_nodes.next().equals(node)) { <add> return true; <add> } <add> } <add> return false; <add> } <ide> }
Java
apache-2.0
799f48816fde17574785f7d3b17354573dfcfdf9
0
marcorei/FirebaseUI-Android,marcorei/FirebaseUI-Android
package com.firebase.uidemo; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.Query; import com.firebase.ui.FirebaseRecyclerViewAdapter; public class RecyclerViewDemoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_demo); final Firebase ref = new Firebase("https://firebaseui.firebaseio.com/chat"); final String name = "PR User"; final Button sendButton = (Button) findViewById(R.id.sendButton); final EditText messageEdit = (EditText) findViewById(R.id.messageEdit); final RecyclerView messages = (RecyclerView) findViewById(R.id.messagesList); final LinearLayoutManager layoutManager = new LinearLayoutManager(this); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Chat chat = new Chat(name, messageEdit.getText().toString()); ref.push().setValue(chat, new Firebase.CompletionListener() { @Override public void onComplete(FirebaseError firebaseError, Firebase firebase) { if (firebaseError != null) { Log.e("FirebaseUI.chat", firebaseError.toString()); } } }); messageEdit.setText(""); } }); final FirebaseRecyclerViewAdapter<Chat, RecyclerView.ViewHolder> adapter = new Adapter( Chat.class, android.R.layout.two_line_list_item, ref, 15, false, name ); layoutManager.setReverseLayout(true); messages.setHasFixedSize(true); messages.setLayoutManager(layoutManager); messages.setAdapter(adapter); messages.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (dy > 0) { return; } if (layoutManager.findLastVisibleItemPosition() < adapter.getItemCount() - 20) { return; } adapter.more(); } }); } public static class Chat { String name; String text; public Chat() { } public Chat(String name, String message) { this.name = name; this.text = message; } public String getName() { return name; } public String getText() { return text; } } public static class HeaderHolder extends RecyclerView.ViewHolder { public HeaderHolder(View itemView) { super(itemView); } } public static class FooterHolder extends RecyclerView.ViewHolder { ProgressBar progressBar; public FooterHolder(View itemView) { super(itemView); progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar); } } public static class ChatHolder extends RecyclerView.ViewHolder { TextView nameView, textView; public ChatHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(android.R.id.text2); textView = (TextView) itemView.findViewById(android.R.id.text1); } } public static class Adapter extends FirebaseRecyclerViewAdapter<Chat, RecyclerView.ViewHolder> { public static final String TAG = Adapter.class.getSimpleName(); public static int VIEW_TYPE_FOOTER = 0; public static int VIEW_TYPE_CONTENT = 1; public static int VIEW_TYPE_HEADER = 2; private String name; private boolean synced; public Adapter(Class<Chat> modelClass, int modelLayout, Query ref, int pageSize, boolean orderASC, String name) { super(modelClass, modelLayout, RecyclerView.ViewHolder.class, ref, pageSize, orderASC); this.name = name; } @Override public int getItemViewType(int position) { if (position == getItemCount() - 1) { return VIEW_TYPE_FOOTER; } else if(position == 0) { return VIEW_TYPE_HEADER; } return VIEW_TYPE_CONTENT; } @Override public int getItemCount() { return super.getItemCount() + 2; } @Override public int getSnapShotOffset() { return 1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if(viewType == VIEW_TYPE_FOOTER) { view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_progress, parent, false); return new FooterHolder(view); } else if(viewType == VIEW_TYPE_HEADER) { view = new LinearLayout(parent.getContext()); view.setMinimumHeight(1); return new HeaderHolder(view); } else { view = LayoutInflater.from(parent.getContext()).inflate(mModelLayout, parent, false); return new ChatHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { int itemViewType = getItemViewType(position); if(itemViewType == VIEW_TYPE_FOOTER) { FooterHolder footerHolder = (FooterHolder) viewHolder; footerHolder.progressBar.setVisibility(synced ? View.GONE : View.VISIBLE); } else if(itemViewType == VIEW_TYPE_CONTENT) { super.onBindViewHolder(viewHolder, position); } } @Override public void populateViewHolder(RecyclerView.ViewHolder viewHolder, Chat chat) { ChatHolder chatView = (ChatHolder) viewHolder; chatView.textView.setText(chat.getText()); chatView.textView.setPadding(10, 0, 10, 0); chatView.nameView.setText(chat.getName()); chatView.nameView.setPadding(10, 0, 10, 15); if (chat.getName().equals(name)) { chatView.textView.setGravity(Gravity.END); chatView.nameView.setGravity(Gravity.END); chatView.nameView.setTextColor(Color.parseColor("#8BC34A")); } else { chatView.textView.setGravity(Gravity.START); chatView.nameView.setGravity(Gravity.START); chatView.nameView.setTextColor(Color.parseColor("#00BCD4")); } } @Override protected void onSyncStatusChanged(boolean synced) { this.synced = synced; notifyItemChanged(getItemCount() - 1); } @Override protected void onArrayError(FirebaseError firebaseError) { Log.d(TAG, firebaseError.toString(), firebaseError.toException()); } } }
app/src/main/java/com/firebase/uidemo/RecyclerViewDemoActivity.java
package com.firebase.uidemo; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.firebase.client.Query; import com.firebase.ui.FirebaseRecyclerViewAdapter; public class RecyclerViewDemoActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_demo); final Firebase ref = new Firebase("https://firebaseui.firebaseio.com/chat"); final String name = "PR User"; final Button sendButton = (Button) findViewById(R.id.sendButton); final EditText messageEdit = (EditText) findViewById(R.id.messageEdit); final RecyclerView messages = (RecyclerView) findViewById(R.id.messagesList); final LinearLayoutManager layoutManager = new LinearLayoutManager(this); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Chat chat = new Chat(name, messageEdit.getText().toString()); ref.push().setValue(chat, new Firebase.CompletionListener() { @Override public void onComplete(FirebaseError firebaseError, Firebase firebase) { if (firebaseError != null) { Log.e("FirebaseUI.chat", firebaseError.toString()); } } }); messageEdit.setText(""); } }); final FirebaseRecyclerViewAdapter<Chat, RecyclerView.ViewHolder> adapter = new Adapter( Chat.class, android.R.layout.two_line_list_item, ref, 8, false, name ); layoutManager.setReverseLayout(true); messages.setHasFixedSize(true); messages.setLayoutManager(layoutManager); messages.setAdapter(adapter); messages.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (dy > 0) { return; } if (layoutManager.findLastVisibleItemPosition() < adapter.getItemCount() - 20) { return; } adapter.more(); } }); } public static class Chat { String name; String text; public Chat() { } public Chat(String name, String message) { this.name = name; this.text = message; } public String getName() { return name; } public String getText() { return text; } } public static class HeaderHolder extends RecyclerView.ViewHolder { ProgressBar progressBar; public HeaderHolder(View itemView) { super(itemView); progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar); } } public static class ChatHolder extends RecyclerView.ViewHolder { TextView nameView, textView; public ChatHolder(View itemView) { super(itemView); nameView = (TextView) itemView.findViewById(android.R.id.text2); textView = (TextView) itemView.findViewById(android.R.id.text1); } } public static class Adapter extends FirebaseRecyclerViewAdapter<Chat, RecyclerView.ViewHolder> { public static final String TAG = Adapter.class.getSimpleName(); public static int VIEW_TYPE_FOOTER = 0; public static int VIEW_TYPE_CONTENT = 1; private String name; private boolean synced; public Adapter(Class<Chat> modelClass, int modelLayout, Query ref, int pageSize, boolean orderASC, String name) { super(modelClass, modelLayout, RecyclerView.ViewHolder.class, ref, pageSize, orderASC); this.name = name; } @Override public int getItemViewType(int position) { if (position == super.getItemCount()) { return VIEW_TYPE_FOOTER; } return VIEW_TYPE_CONTENT; } @Override public int getItemCount() { return super.getItemCount() + 1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view; if(viewType == VIEW_TYPE_FOOTER) { view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_progress, parent, false); return new HeaderHolder(view); } else { view = LayoutInflater.from(parent.getContext()).inflate(mModelLayout, parent, false); return new ChatHolder(view); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { int itemViewType = getItemViewType(position); if(itemViewType == VIEW_TYPE_FOOTER) { HeaderHolder headerHolder = (HeaderHolder) viewHolder; headerHolder.progressBar.setVisibility(synced ? View.GONE : View.VISIBLE); } else if(itemViewType == VIEW_TYPE_CONTENT) { super.onBindViewHolder(viewHolder, position); } } @Override public void populateViewHolder(RecyclerView.ViewHolder viewHolder, Chat chat) { ChatHolder chatView = (ChatHolder) viewHolder; chatView.textView.setText(chat.getText()); chatView.textView.setPadding(10, 0, 10, 0); chatView.nameView.setText(chat.getName()); chatView.nameView.setPadding(10, 0, 10, 15); if (chat.getName().equals(name)) { chatView.textView.setGravity(Gravity.END); chatView.nameView.setGravity(Gravity.END); chatView.nameView.setTextColor(Color.parseColor("#8BC34A")); } else { chatView.textView.setGravity(Gravity.START); chatView.nameView.setGravity(Gravity.START); chatView.nameView.setTextColor(Color.parseColor("#00BCD4")); } } @Override protected void onSyncStatusChanged(boolean synced) { this.synced = synced; notifyItemChanged(getItemCount() - 1); } @Override protected void onArrayError(FirebaseError firebaseError) { Log.d(TAG, firebaseError.toString(), firebaseError.toException()); } } }
add header for a sticky list
app/src/main/java/com/firebase/uidemo/RecyclerViewDemoActivity.java
add header for a sticky list
<ide><path>pp/src/main/java/com/firebase/uidemo/RecyclerViewDemoActivity.java <ide> import android.view.ViewGroup; <ide> import android.widget.Button; <ide> import android.widget.EditText; <add>import android.widget.LinearLayout; <ide> import android.widget.ProgressBar; <ide> import android.widget.TextView; <del>import android.widget.Toast; <ide> <ide> import com.firebase.client.Firebase; <ide> import com.firebase.client.FirebaseError; <ide> Chat.class, <ide> android.R.layout.two_line_list_item, <ide> ref, <del> 8, <add> 15, <ide> false, <ide> name ); <ide> <ide> } <ide> } <ide> <del> public static class HeaderHolder extends RecyclerView.ViewHolder { <add> public static class HeaderHolder extends RecyclerView.ViewHolder { <add> public HeaderHolder(View itemView) { <add> super(itemView); <add> } <add> } <add> <add> public static class FooterHolder extends RecyclerView.ViewHolder { <ide> ProgressBar progressBar; <ide> <del> public HeaderHolder(View itemView) { <add> public FooterHolder(View itemView) { <ide> super(itemView); <ide> progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar); <ide> } <ide> <ide> public static int VIEW_TYPE_FOOTER = 0; <ide> public static int VIEW_TYPE_CONTENT = 1; <add> public static int VIEW_TYPE_HEADER = 2; <ide> private String name; <ide> private boolean synced; <ide> <ide> <ide> @Override <ide> public int getItemViewType(int position) { <del> if (position == super.getItemCount()) { <add> if (position == getItemCount() - 1) { <ide> return VIEW_TYPE_FOOTER; <ide> } <add> else if(position == 0) { <add> return VIEW_TYPE_HEADER; <add> } <ide> return VIEW_TYPE_CONTENT; <ide> } <ide> <ide> @Override <ide> public int getItemCount() { <del> return super.getItemCount() + 1; <add> return super.getItemCount() + 2; <add> } <add> <add> @Override <add> public int getSnapShotOffset() { <add> return 1; <ide> } <ide> <ide> @Override <ide> View view; <ide> if(viewType == VIEW_TYPE_FOOTER) { <ide> view = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_holder_progress, parent, false); <add> return new FooterHolder(view); <add> } <add> else if(viewType == VIEW_TYPE_HEADER) { <add> view = new LinearLayout(parent.getContext()); <add> view.setMinimumHeight(1); <ide> return new HeaderHolder(view); <ide> } <ide> else { <ide> public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { <ide> int itemViewType = getItemViewType(position); <ide> if(itemViewType == VIEW_TYPE_FOOTER) { <del> HeaderHolder headerHolder = (HeaderHolder) viewHolder; <del> headerHolder.progressBar.setVisibility(synced ? View.GONE : View.VISIBLE); <add> FooterHolder footerHolder = (FooterHolder) viewHolder; <add> footerHolder.progressBar.setVisibility(synced ? View.GONE : View.VISIBLE); <ide> } <ide> else if(itemViewType == VIEW_TYPE_CONTENT) { <ide> super.onBindViewHolder(viewHolder, position);
Java
apache-2.0
f6bbd92c86b7e606d25a538fcf682abb67fd3510
0
semonte/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,izonder/intellij-community,caot/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,holmes/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,allotria/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,caot/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,clumsy/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,supersven/intellij-community,kdwink/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,kdwink/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,jagguli/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,ryano144/intellij-community,dslomov/intellij-community,asedunov/intellij-community,samthor/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,holmes/intellij-community,xfournet/intellij-community,apixandru/intellij-community,diorcety/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,caot/intellij-community,holmes/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,ryano144/intellij-community,apixandru/intellij-community,robovm/robovm-studio,signed/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,caot/intellij-community,semonte/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,izonder/intellij-community,retomerz/intellij-community,vladmm/intellij-community,asedunov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,allotria/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,hurricup/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,izonder/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,dslomov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,signed/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,slisson/intellij-community,adedayo/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,signed/intellij-community,signed/intellij-community,adedayo/intellij-community,samthor/intellij-community,dslomov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,ryano144/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,holmes/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,kdwink/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,Lekanich/intellij-community,izonder/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,semonte/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,izonder/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,izonder/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,slisson/intellij-community,FHannes/intellij-community,semonte/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,da1z/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,amith01994/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,SerCeMan/intellij-community,signed/intellij-community,gnuhub/intellij-community,samthor/intellij-community,samthor/intellij-community,samthor/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,xfournet/intellij-community,clumsy/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,hurricup/intellij-community,slisson/intellij-community,xfournet/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,holmes/intellij-community,kdwink/intellij-community,petteyg/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,gnuhub/intellij-community,slisson/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,kool79/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,da1z/intellij-community,adedayo/intellij-community,jagguli/intellij-community,da1z/intellij-community,holmes/intellij-community,gnuhub/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,signed/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,signed/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,caot/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,adedayo/intellij-community,izonder/intellij-community,da1z/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,da1z/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,semonte/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,youdonghai/intellij-community,allotria/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,izonder/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,asedunov/intellij-community,samthor/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,caot/intellij-community,dslomov/intellij-community,samthor/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,blademainer/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,hurricup/intellij-community,kool79/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,supersven/intellij-community,youdonghai/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,amith01994/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,xfournet/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ryano144/intellij-community,signed/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,kdwink/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,vladmm/intellij-community,ryano144/intellij-community,asedunov/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,signed/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,clumsy/intellij-community,samthor/intellij-community,slisson/intellij-community,signed/intellij-community,apixandru/intellij-community,hurricup/intellij-community,supersven/intellij-community,caot/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,fnouama/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,supersven/intellij-community,ryano144/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,semonte/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,blademainer/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,caot/intellij-community,kool79/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,supersven/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,gnuhub/intellij-community,slisson/intellij-community,retomerz/intellij-community,caot/intellij-community,orekyuu/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,FHannes/intellij-community,fnouama/intellij-community,diorcety/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,holmes/intellij-community,Distrotech/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,FHannes/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,samthor/intellij-community,clumsy/intellij-community,slisson/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,holmes/intellij-community,xfournet/intellij-community,retomerz/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,supersven/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,jagguli/intellij-community,hurricup/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,signed/intellij-community,allotria/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,kool79/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,holmes/intellij-community,vladmm/intellij-community,slisson/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community
package org.jetbrains.plugins.ipnb.format; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.ipnb.format.cells.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class IpnbParser { private static final Logger LOG = Logger.getInstance(IpnbParser.class); private static final Gson gson = initGson(); @NotNull private static Gson initGson() { GsonBuilder builder = new GsonBuilder(); return builder.create(); } @NotNull public static CodeCell parseIpnbCell(@NotNull String item) throws IOException { CodeCell ipnbCell = gson.fromJson(item, CodeCell.class); return ipnbCell; } @NotNull public static IpnbFile parseIpnbFile(@NotNull String fileText) throws IOException { IpnbFileRaw rawFile = gson.fromJson(fileText, IpnbFileRaw.class); List<IpnbCell> cells = new ArrayList<IpnbCell>(); final IpnbWorksheet[] worksheets = rawFile.worksheets; for (IpnbWorksheet worksheet : worksheets) { final IpnbCellRaw[] rawCells = worksheet.cells; for (IpnbCellRaw rawCell : rawCells) { cells.add(rawCell.createCell()); } } return new IpnbFile(cells); } private static class IpnbFileRaw { IpnbWorksheet[] worksheets; } private static class IpnbWorksheet { IpnbCellRaw[] cells; } private static class IpnbCellRaw { String cell_type; String[] source; String[] input; String language; CellOutput[] outputs; public IpnbCell createCell() { final IpnbCell cell; if (cell_type.equals("markdown")) { cell = new MarkdownCell(); } else if (cell_type.equals("code")) { cell = new CodeCell(); } else if (cell_type.equals("raw")) { cell = new RawCell(); } else if (cell_type.equals("heading")) { cell = new HeadingCell(); } else { cell = null; } return cell; } } private static class CellOutput { String output_type; String[] text; } }
src/org/jetbrains/plugins/ipnb/format/IpnbParser.java
package org.jetbrains.plugins.ipnb.format; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.ipnb.format.cells.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class IpnbParser { private static final Logger LOG = Logger.getInstance(IpnbParser.class); private static final Gson gson = initGson(); @NotNull private static Gson initGson() { GsonBuilder builder = new GsonBuilder(); return builder.create(); } @NotNull public static CodeCell parseIpnbCell(@NotNull String item) throws IOException { CodeCell ipnbCell = gson.fromJson(item, CodeCell.class); return ipnbCell; } @NotNull public static IpnbFile parseIpnbFile(@NotNull String fileText) throws IOException { IpnbFileRaw rawFile = gson.fromJson(fileText, IpnbFileRaw.class); List<IpnbCell> cells = new ArrayList<IpnbCell>(); final IpnbWorksheet[] worksheets = rawFile.worksheets; for (IpnbWorksheet worksheet : worksheets) { final IpnbCellRaw[] rawCells = worksheet.cells; for (IpnbCellRaw rawCell : rawCells) { cells.add(rawCell.createCell()); } } return new IpnbFile(cells); } private static class IpnbFileRaw { IpnbWorksheet[] worksheets; } private static class IpnbWorksheet { IpnbCellRaw[] cells; } private static class IpnbCellRaw { String cell_type; String[] source; public IpnbCell createCell() { final IpnbCell cell; if (cell_type.equals("markdown")) { cell = new MarkdownCell(); } else if (cell_type.equals("code")) { cell = new CodeCell(); } else if (cell_type.equals("raw")) { cell = new RawCell(); } else if (cell_type.equals("heading")) { cell = new HeadingCell(); } else { cell = null; } return cell; } } }
added cell output
src/org/jetbrains/plugins/ipnb/format/IpnbParser.java
added cell output
<ide><path>rc/org/jetbrains/plugins/ipnb/format/IpnbParser.java <ide> private static class IpnbWorksheet { <ide> IpnbCellRaw[] cells; <ide> } <del> <ide> private static class IpnbCellRaw { <ide> String cell_type; <ide> String[] source; <add> String[] input; <add> String language; <add> CellOutput[] outputs; <ide> <ide> public IpnbCell createCell() { <ide> final IpnbCell cell; <ide> return cell; <ide> } <ide> } <add> private static class CellOutput { <add> String output_type; <add> String[] text; <add> } <ide> }
Java
mit
39cab16605e63aaed1e6a8f5f0ac55f95a3982e5
0
stevengreens10/OlympicHeroes
package me.NodeDigital.OlympicHeroes.command; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.NodeDigital.OlympicHeroes.Variables; import me.NodeDigital.OlympicHeroes.player.OHPlayer; public class OHCommand implements CommandExecutor{ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player player = (Player) sender; OHPlayer ohPlayer = new OHPlayer(player); if(args.length == 0) { player.sendMessage("---------------------"); for(String god : Variables.GODS) { player.sendMessage(god + " : " + ohPlayer.getXP(god) + " XP : " + "Lvl " + ohPlayer.getLevel(god)); } }else if(args.length >= 3) { if(args[0].equalsIgnoreCase("set")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { String godName = args[2]; godName = godName.toLowerCase(); godName = godName.substring(0,1).toUpperCase() + godName.substring(1); boolean validGod = false; for(String god : Variables.GODS) { if(god.equalsIgnoreCase(godName)) { validGod = true; } } if(validGod) { try { int xp = Integer.parseInt(args[3]); new OHPlayer(p).setXP(xp, godName, true); player.sendMessage("You set " + playerName + "'s XP for " + godName + " to " + xp + "."); }catch(Exception e) { player.sendMessage("The XP amount must be a valid number!"); } }else { player.sendMessage(godName + " is not a valid god!"); } }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } } }else if(args.length >= 2) { if(args[0].equalsIgnoreCase("reset")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { OHPlayer ohP = new OHPlayer(p); for(String god : Variables.GODS) { ohP.setXP(0, god, true); } player.sendMessage(playerName + "'s XP has been reset!"); }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } }else if(args[0].equalsIgnoreCase("view")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { OHPlayer ohP = new OHPlayer(p); player.sendMessage("---------" + p.getName() + "---------"); for(String god : Variables.GODS) { player.sendMessage(god + " : " + ohP.getXP(god) + " XP : " + "Lvl " + ohP.getLevel(god)); } }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } } } else { String arg = args[0]; String god = ""; for(String g : Variables.GODS) { if(arg.equalsIgnoreCase(g)) { god = g; break; } } if(god.length() >= 1) { for(String s : Variables.GOD_INFO.get(god)) { player.sendMessage(s); } } } } return false; } }
me/NodeDigital/OlympicHeroes/command/OHCommand.java
package me.NodeDigital.OlympicHeroes.command; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.NodeDigital.OlympicHeroes.Variables; import me.NodeDigital.OlympicHeroes.player.OHPlayer; public class OHCommand implements CommandExecutor{ @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(sender instanceof Player) { Player player = (Player) sender; OHPlayer ohPlayer = new OHPlayer(player); if(args.length == 0) { player.sendMessage("---------------------"); for(String god : Variables.GODS) { player.sendMessage(god + " : " + ohPlayer.getXP(god) + " XP : " + "Lvl " + ohPlayer.getLevel(god)); } }else if(args.length >= 3) { if(args[0].equalsIgnoreCase("set")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { String godName = args[2]; godName = godName.toLowerCase(); godName = godName.substring(0,1).toUpperCase() + godName.substring(1); boolean validGod = false; for(String god : Variables.GODS) { if(god.equalsIgnoreCase(godName)) { validGod = true; } } if(validGod) { try { int xp = Integer.parseInt(args[3]); new OHPlayer(p).setXP(xp, godName, true); player.sendMessage("You set " + playerName + "'s XP for " + godName + " to " + xp + "."); }catch(Exception e) { player.sendMessage("The XP amount must be a valid number!"); } }else { player.sendMessage(godName + " is not a valid god!"); } }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } } }else if(args.length >= 2) { if(args[0].equalsIgnoreCase("reset")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { OHPlayer ohP = new OHPlayer(p); for(String god : Variables.GODS) { ohP.setXP(0, god, true); } player.sendMessage(playerName + "'s XP has been reset!"); }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } }else if(args[0].equalsIgnoreCase("view")) { if(player.hasPermission("oh.admin")) { String playerName = args[1]; Player p = Bukkit.getServer().getPlayer(playerName); if(p != null) { OHPlayer ohP = new OHPlayer(p); player.sendMessage("---------" + p.getName() + "---------"); for(String god : Variables.GODS) { player.sendMessage(god + " : " + ohP.getXP(god) + " XP : " + "Lvl " + ohP.getLevel(god)); } }else { player.sendMessage("Player does not exist!"); } }else { player.sendMessage("You do not have permission!"); } } else { String arg = args[0]; String god = ""; for(String g : Variables.GODS) { if(arg.equalsIgnoreCase(g)) { god = g; break; } } if(god.length() >= 1) { for(String s : Variables.GOD_INFO.get(god)) { player.sendMessage(s); } } } } } return false; } }
Fix help commands
me/NodeDigital/OlympicHeroes/command/OHCommand.java
Fix help commands
<ide><path>e/NodeDigital/OlympicHeroes/command/OHCommand.java <ide> }else { <ide> player.sendMessage("You do not have permission!"); <ide> } <del> } else { <del> String arg = args[0]; <del> <del> String god = ""; <del> <del> for(String g : Variables.GODS) { <del> if(arg.equalsIgnoreCase(g)) { <del> god = g; <del> break; <del> } <add> } <add> } else { <add> String arg = args[0]; <add> <add> String god = ""; <add> <add> for(String g : Variables.GODS) { <add> if(arg.equalsIgnoreCase(g)) { <add> god = g; <add> break; <ide> } <del> <del> if(god.length() >= 1) { <del> for(String s : Variables.GOD_INFO.get(god)) { <del> player.sendMessage(s); <del> } <add> } <add> <add> if(god.length() >= 1) { <add> for(String s : Variables.GOD_INFO.get(god)) { <add> player.sendMessage(s); <ide> } <ide> } <ide> }
JavaScript
mit
48baad46043d660739f72b2c58fc0aa25aaa3ca5
0
faithtech/website,faithtech/website
var dict = { // header 'What is Checkin+ ?': { zhtw: 'Checkin+ 是什麼?', en: 'What is Checkin+ ?' }, 'How to work?': { zhtw: '如何合作?', en: 'How to work?' }, 'Our Services': { zhtw: '加值服務', en: 'Our Services' }, 'About': { zhtw: '關於我們', en: 'About' }, 'Lang': { zhtw: '語言', en: 'Lang' }, // slogan 要精簡 '・Exhibition leader': { zhtw: '・會展科技領導者', en: '・Exhibition leader' }, '・Fully functional': { zhtw: '・全功能簽到服務', en: '・Fully functional' }, '・More smoothly': { zhtw: '・讓活動更加順暢', en: '・More smoothly' }, 'Send Order': { zhtw: '寄信預約', en: 'Send Order' }, // What is Checkin+ ? 'Checkin+ is little helper activity report, regardless of how much human activity is, Checkin+ can help you save a lot of human volunteers, so that your activities are no longer running around in circles': { zhtw: 'Checkin+ 是活動報到小助手,不論是多少人的活動,Checkin+ 都可以幫你節省大量的人力志工,讓您的活動不再手忙腳亂', en: 'Checkin+ is little helper activity report, regardless of how much human activity is, Checkin+ can help you save a lot of human volunteers, so that your activities are no longer running around in circles' }, 'Generating statistics': { zhtw: '一鍵產生統計表', en: 'Generating statistics' }, 'There are sign-in sheet to render an account, a key production statistics, end of the event immediately reimbursement': { zhtw: '有簽到表才能報帳,一鍵產統計表,活動結束立刻報帳', en: 'There are sign-in sheet to render an account, a key production statistics, end of the event immediately reimbursement' }, 'Save manpower': { zhtw: '節省人力', en: 'Save manpower' }, 'With the most streamlined manpower, so that a large number of participants complete report': { zhtw: '用最精簡的人力,讓大量的與會者完成報到', en: 'With the most streamlined manpower, so that a large number of participants complete report' }, 'ReMarketing': { zhtw: '再次行銷', en: 'ReMarketing' }, 'Allowing you to quickly and accurate interactive and participants': { zhtw: '讓您快速而精準的和與會者互動', en: 'Allowing you to quickly and accurate interactive and participants' }, // Checkin+ 如何和您合作? 'How to work with you?': { zhtw: '如何和您合作?', en: 'How to work with you?' }, 'Checkin+ will send someone to the site to help you install the system, six minutes to complete the installation. Just write down a single appointment, the person immediately and contact you': { zhtw: 'Checkin+ 會派專人到現場協助您安裝系統,六分鐘就能完成安裝。只要寫下預約單,專人立即和您聯絡', en: 'Checkin+ will send someone to the site to help you install the system, six minutes to complete the installation. Just write down a single appointment, the person immediately and contact you' }, 'Fill a single appointment': { zhtw: '填寫預約單', en: 'Fill a single appointment' }, 'Discuss project needs': { zhtw: '討論專案需求', en: 'Discuss project needs' }, 'To install in meeting': { zhtw: '到活動會場安裝', en: 'To install in meeting' }, // Checkin+ 還可以幫您什麼? 'What can also help you?': { zhtw: '還可以幫您什麼?', en: 'What can also help you?' }, "Checkin+ hope in addition to saving you hours of manpower, but also that you make more statistical analysis and online services, so you'll know exactly activity effectiveness, convenience and participants for further interaction": { zhtw: 'Checkin+ 希望除了節省您的人力時間,還可以為您做更多統計分析和線上服務,讓您清楚知道活動效益,便捷和與會者做進一步的互動', en: "Checkin+ hope in addition to saving you hours of manpower, but also that you make more statistical analysis and online services, so you'll know exactly activity effectiveness, convenience and participants for further interaction" }, 'Questionnaire': { zhtw: '提問卷', en: 'Questionnaire' }, 'Without pen and paper, you can ask the online satisfaction questionnaire so that effective recovery up to a hundred percent': { zhtw: '不用紙筆,線上就能詢問滿意度,讓有效問卷回收高達百分百', en: 'Without pen and paper, you can ask the online satisfaction questionnaire so that effective recovery up to a hundred percent' }, 'Cloud attendance, conference materials made immediately': { zhtw: '雲端簽到,立即取得會議資料', en: 'Cloud attendance, conference materials made immediately' }, 'Too late to participate or not participate in the participants, with the online portal sign, just like online check of the aircraft in. Reached the scene do not line up, and immediately enter the venue, the line can also be made to handouts and video files': { zhtw: '來不及參加,或是不能參加的與會者,用線上 portal 簽到,就有如飛機的線上 check in。達到現場不用排隊,立刻進會場,線上也能取得到講義和影音文件', en: 'Too late to participate or not participate in the participants, with the online portal sign, just like online check of the aircraft in. Reached the scene do not line up, and immediately enter the venue, the line can also be made to handouts and video files' }, 'Flexible expansion station': { zhtw: '彈性擴充簽到站', en: 'Flexible expansion station' }, 'Conferences have always queuing up for admission Well? Flexible expansion station sign, so you can increase depending on the number of check-in stations, so that participants can fast track into the hall, no longer have to queue at the door card': { zhtw: '大型會議總是得排隊進場嘛?彈性擴充簽到站,讓您可以視人數增加簽到站,讓與會者可以快速通關進會場,再也不用卡在門口排隊', en: 'Conferences have always queuing up for admission Well? Flexible expansion station sign, so you can increase depending on the number of check-in stations, so that participants can fast track into the hall, no longer have to queue at the door card' }, 'No network can immediately work': { zhtw: '不用網路就能立刻作業', en: 'No network can immediately work' }, 'The web site is not good, but also to complete the sign thing? Checkin+ No problem, our system can communicate with each other, so even if there is no network can be completed sign': { zhtw: '現場網路不好,也能完成簽到嘛?Checkin+ 沒問題,我們系統可以互相通訊,所以即使沒有網路也能完成簽到', en: 'The web site is not good, but also to complete the sign thing? Checkin+ No problem, our system can communicate with each other, so even if there is no network can be completed sign' }, 'Private Cloud Share': { zhtw: '私有雲分享', en: 'Private Cloud Share' }, 'Only participants can see the file, you use packaged private cloud up!': { zhtw: '只有與會者才能看到的文件,就用私有雲打包起來吧!', en: 'Only participants can see the file, you use packaged private cloud up!' }, 'Rapid exchange business cards': { zhtw: '快速交換名片', en: 'Rapid exchange business cards' }, 'Participants can quickly and new acquaintances through the exchange of business cards Checkin+, strung commercial link': { zhtw: '透過 Checkin+,與會者可以快速和新認識的朋友交換名片,串起商業的連結', en: 'Participants can quickly and new acquaintances through the exchange of business cards Checkin+, strung commercial link' }, 'Value-added data services': { zhtw: '加值數據服務', en: 'Value-added data services' }, 'Big data statistical analysis, opinion surveys behavior analysis, marketing forecasting analysis, customer attribute points west, supporting marketing programs, integrating exhibitors moving hot line data analysis. Checkin+ gives you precise attack next!': { zhtw: '大數據資料統計分析、意見調查行為分析、行銷預測分析、客戶屬性分西、行銷配套方案、整合參展動線熱點數據分析。Checkin+ 讓您精準出擊下一步!', en: 'Big data statistical analysis, opinion surveys behavior analysis, marketing forecasting analysis, customer attribute points west, supporting marketing programs, integrating exhibitors moving hot line data analysis. Checkin+ gives you precise attack next!' }, 'Exhibition co-periphery good': { zhtw: '會展週邊共好', en: 'Exhibition co-periphery good' }, 'Valid data marketing programs: Registration of participants tickets, discount hotel reservations, convention surrounding shopping, dining, entertainment, transportation, restaurants and other services supporting the integration of communication, once you are contracted out!': { zhtw: '有效數據行銷方案:報到參加者機票、飯店訂房折扣、會展週邊購物、餐飲、娛樂、交通、飯店通訊整合等服務配套,一次包給您!', en: 'Valid data marketing programs: Registration of participants tickets, discount hotel reservations, convention surrounding shopping, dining, entertainment, transportation, restaurants and other services supporting the integration of communication, once you are contracted out!' }, // 聽聽用戶怎麼說 'Listen to how users say': { zhtw: '聽聽用戶怎麼說', en: 'Listen to how users say' }, 'Large Conference Registration volunteers need 20--30 people, with Checkin+ now only 10 people is enough! 1/3 Human save it!': { zhtw: '大型會議報到志工都需要20 - 30 人,有了 Checkin+ 現在只要 10個人就夠了!人力節省 1/3 呢!', en: 'Large Conference Registration volunteers need 20--30 people, with Checkin+ now only 10 people is enough! 1/3 Human save it!' }, '- xxxx event hoster': { zhtw: '- xxxx 活動主辦人', en: '- xxxx event hoster' }, 'After the event, always take a long time to sort out the questionnaire and lists After Checkin+, faster analysis was again accurate marketing': { zhtw: '活動結束後,總是要花很長時間整理問卷和名單,用 Checkin+ 後,可以更快分析與會者,再次精準行銷', en: 'After the event, always take a long time to sort out the questionnaire and lists After Checkin+, faster analysis was again accurate marketing' }, '- xxxx Marketing Manager': { zhtw: '- xxxx 行銷經理', en: '- xxxx Marketing Manager' }, 'Participate in activities always stuck in the door line, automatic check-in system can quickly allow members Admission to feel very convenient': { zhtw: '參加活動總是卡在門口排隊,自動簽到系統可以快速讓會員入場,覺得相當方便', en: 'Participate in activities always stuck in the door line, automatic check-in system can quickly allow members Admission to feel very convenient' }, '- xxxx event participants': { zhtw: '- xxxx 活動參加者', en: '- xxxx event participants' }, // footer 'Faithtech Co., Ltd.': { zhtw: '誠義資訊股份有限公司', en: 'Faithtech Co., Ltd.' }, 'Tel:': { zhtw: '電話:', en: 'Tel:' }, 'Email:': { zhtw: '信箱:', en: 'Email:' }, 'Add:': { zhtw: '地址:', en: 'Add:' }, '10658 6F., No.153, Sec. 3, Xinyi Rd., Da’an Dist., Taipei City 106, Taiwan (R.O.C.)': { zhtw: '10658 台北市大安區信義路三段153號6樓', en: '10658 6F., No.153, Sec. 3, Xinyi Rd., Da’an Dist., Taipei City 106, Taiwan (R.O.C.)' }, // 預約表單 "Hello, please help us fill in the form and we'll contact you as soon as possible, thank you!": { zhtw: '您好,請協助我們填寫表單,我們會盡快和您聯絡,謝謝!', en: "Hello, please help us fill in the form and we'll contact you as soon as possible, thank you!" }, 'Full name': { zhtw: '您的大名', en: 'Full name' }, 'Phone': { zhtw: '聯絡電話', en: 'Phone' }, 'Email': { zhtw: '聯絡信箱', en: 'Email' }, 'Event name': { zhtw: '活動名稱', en: 'Event name' }, 'Event time': { zhtw: '活動時間', en: 'Event time' }, 'From': { zhtw: '從', en: 'From' }, 'To': { zhtw: '到', en: 'To' }, 'Y': { zhtw: '年', en: 'Y' }, 'M': { zhtw: '月', en: 'M' }, 'D': { zhtw: '日', en: 'D' }, 'Event address': { zhtw: '活動地點', en: 'Event address' }, 'Estimated number of activities': { zhtw: '預估活動人數', en: 'Estimated number of activities' }, 'other': { zhtw: '其他', en: 'other' }, // form notice 'Form has been sent': { zhtw: '表單已送出', en: 'Form has been sent' }, "Thank you for your patience to fill, and we'll contact you as soon as possible! Thank you!": { zhtw: '表感謝您耐心填寫,我們會盡快和您聯絡!謝謝!', en: "Thank you for your patience to fill, and we'll contact you as soon as possible! Thank you!" }, 'OK': { zhtw: '確定', en: 'OK' }, 'Woops!': { zhtw: '出了一些問題!', en: 'Woops!' }, 'Sorry,something has gone wrong, you may want to send a letter to [email protected] We will contact you as soon as possible! Thank you!': { zhtw: '抱歉,出了一些問題,您可以先寄信到 [email protected] 我們會盡快和您聯絡!謝謝!', en:'Sorry, something has gone wrong, you may want to send a letter to [email protected] We will contact you as soon as possible! Thank you!' }, }
source/js/jquery.translate.text.js
var dict = { // header 'What is Checkin+ ?': { zhtw: 'Checkin+ 是什麼?', en: 'What is Checkin+ ?' }, 'How to work?': { zhtw: '如何合作?', en: 'How to work?' }, 'Our Services': { zhtw: '加值服務', en: 'Our Services' }, 'About': { zhtw: '關於我們', en: 'About' }, 'Lang': { zhtw: '語言', en: 'Lang' }, // slogan 要精簡 '・Exhibition leader': { zhtw: '・會展科技領導者', en: '・Exhibition leader' }, '・Fully functional': { zhtw: '・全功能簽到服務', en: '・Fully functional' }, '・More smoothly': { zhtw: '・讓活動更加順暢', en: '・More smoothly' }, 'Send Order': { zhtw: '寄信預約', en: 'Send Order' }, // What is Checkin+ ? 'Checkin+ is little helper activity report, regardless of how much human activity is, Checkin+ can help you save a lot of human volunteers, so that your activities are no longer running around in circles': { zhtw: 'Checkin+ 是活動報到小助手,不論是多少人的活動,Checkin+ 都可以幫你節省大量的人力志工,讓您的活動不再手忙腳亂', en: 'Checkin+ is little helper activity report, regardless of how much human activity is, Checkin+ can help you save a lot of human volunteers, so that your activities are no longer running around in circles' }, 'Generating statistics': { zhtw: '一鍵產生統計表', en: 'Generating statistics' }, 'There are sign-in sheet to render an account, a key production statistics, end of the event immediately reimbursement': { zhtw: '有簽到表才能報帳,一鍵產統計表,活動結束立刻報帳', en: 'There are sign-in sheet to render an account, a key production statistics, end of the event immediately reimbursement' }, 'Save manpower': { zhtw: '節省人力', en: 'Save manpower' }, 'With the most streamlined manpower, so that a large number of participants complete report': { zhtw: '用最精簡的人力,讓大量的與會者完成報到', en: 'With the most streamlined manpower, so that a large number of participants complete report' }, 'ReMarketing': { zhtw: '再次行銷', en: 'ReMarketing' }, 'Allowing you to quickly and accurate interactive and participants': { zhtw: '讓您快速而精準的和與會者互動', en: 'Allowing you to quickly and accurate interactive and participants' }, // Checkin+ 如何和您合作? 'How to work with you?': { zhtw: '如何和您合作?', en: 'How to work with you?' }, 'Checkin+ will send someone to the site to help you install the system, six minutes to complete the installation. Just write down a single appointment, the person immediately and contact you': { zhtw: 'Checkin+ 會派專人到現場協助您安裝系統,六分鐘就能完成安裝。只要寫下預約單,專人立即和您聯絡', en: 'Checkin+ will send someone to the site to help you install the system, six minutes to complete the installation. Just write down a single appointment, the person immediately and contact you' }, 'Fill a single appointment': { zhtw: '填寫預約單', en: 'Fill a single appointment' }, 'Discuss project needs': { zhtw: '討論專案需求', en: 'Discuss project needs' }, 'To install in meeting': { zhtw: '到活動會場安裝', en: 'To install in meeting' }, // Checkin+ 還可以幫您什麼? 'What can also help you?': { zhtw: '還可以幫您什麼?', en: 'What can also help you?' }, "Checkin+ hope in addition to saving you hours of manpower, but also that you make more statistical analysis and online services, so you'll know exactly activity effectiveness, convenience and participants for further interaction": { zhtw: 'Checkin+ 希望除了節省您的人力時間,還可以為您做更多統計分析和線上服務,讓您清楚知道活動效益,便捷和與會者做進一步的互動', en: "Checkin+ hope in addition to saving you hours of manpower, but also that you make more statistical analysis and online services, so you'll know exactly activity effectiveness, convenience and participants for further interaction" }, 'Questionnaire': { zhtw: '提問卷', en: 'Questionnaire' }, 'Without pen and paper, you can ask the online satisfaction questionnaire so that effective recovery up to a hundred percent': { zhtw: '不用紙筆,線上就能詢問滿意度,讓有效問卷回收高達百分百', en: 'Without pen and paper, you can ask the online satisfaction questionnaire so that effective recovery up to a hundred percent' }, 'Cloud attendance, conference materials made immediately': { zhtw: '雲端簽到,立即取得會議資料', en: 'Cloud attendance, conference materials made immediately' }, 'Too late to participate or not participate in the participants, with the online portal sign, just like online check of the aircraft in. Reached the scene do not line up, and immediately enter the venue, the line can also be made to handouts and video files': { zhtw: '來不及參加,或是不能參加的與會者,用線上 portal 簽到,就有如飛機的線上 check in。達到現場不用排隊,立刻進會場,線上也能取得到講義和影音文件', en: 'Too late to participate or not participate in the participants, with the online portal sign, just like online check of the aircraft in. Reached the scene do not line up, and immediately enter the venue, the line can also be made to handouts and video files' }, 'Flexible expansion station': { zhtw: '彈性擴充簽到站', en: 'Flexible expansion station' }, 'Conferences have always queuing up for admission Well? Flexible expansion station sign, so you can increase depending on the number of check-in stations, so that participants can fast track into the hall, no longer have to queue at the door card': { zhtw: '大型會議總是得排隊進場嘛?彈性擴充簽到站,讓您可以視人數增加簽到站,讓與會者可以快速通關進會場,再也不用卡在門口排隊', en: 'Conferences have always queuing up for admission Well? Flexible expansion station sign, so you can increase depending on the number of check-in stations, so that participants can fast track into the hall, no longer have to queue at the door card' }, 'No network can immediately work': { zhtw: '不用網路就能立刻作業', en: 'No network can immediately work' }, 'The web site is not good, but also to complete the sign thing? Checkin+ No problem, our system can communicate with each other, so even if there is no network can be completed sign': { zhtw: '現場網路不好,也能完成簽到嘛?Checkin+ 沒問題,我們系統可以互相通訊,所以即使沒有網路也能完成簽到', en: 'The web site is not good, but also to complete the sign thing? Checkin+ No problem, our system can communicate with each other, so even if there is no network can be completed sign' }, 'Private Cloud Share': { zhtw: '私有雲分享', en: 'Private Cloud Share' }, 'Only participants can see the file, you use packaged private cloud up!': { zhtw: '只有與會者才能看到的文件,就用私有雲打包起來吧!', en: 'Only participants can see the file, you use packaged private cloud up!' }, 'Rapid exchange business cards': { zhtw: '快速交換名片', en: 'Rapid exchange business cards' }, 'Participants can quickly and new acquaintances through the exchange of business cards Checkin+, strung commercial link': { zhtw: '透過 Checkin+,與會者可以快速和新認識的朋友交換名片,串起商業的連結', en: 'Participants can quickly and new acquaintances through the exchange of business cards Checkin+, strung commercial link' }, 'Value-added data services': { zhtw: '加值數據服務', en: 'Value-added data services' }, 'Big data statistical analysis, opinion surveys behavior analysis, marketing forecasting analysis, customer attribute points west, supporting marketing programs, integrating exhibitors moving hot line data analysis. Checkin+ gives you precise attack next!': { zhtw: '大數據資料統計分析、意見調查行為分析、行銷預測分析、客戶屬性分西、行銷配套方案、整合參展動線熱點數據分析。Checkin+ 讓您精準出擊下一步!', en: 'Big data statistical analysis, opinion surveys behavior analysis, marketing forecasting analysis, customer attribute points west, supporting marketing programs, integrating exhibitors moving hot line data analysis. Checkin+ gives you precise attack next!' }, 'Exhibition co-periphery good': { zhtw: '會展週邊共好', en: 'Exhibition co-periphery good' }, 'Valid data marketing programs: Registration of participants tickets, discount hotel reservations, convention surrounding shopping, dining, entertainment, transportation, restaurants and other services supporting the integration of communication, once you are contracted out!': { zhtw: '有效數據行銷方案:報到參加者機票、飯店訂房折扣、會展週邊購物、餐飲、娛樂、交通、飯店通訊整合等服務配套,一次包給您!', en: 'Valid data marketing programs: Registration of participants tickets, discount hotel reservations, convention surrounding shopping, dining, entertainment, transportation, restaurants and other services supporting the integration of communication, once you are contracted out!' }, // 聽聽用戶怎麼說 'Listen to how users say': { zhtw: '聽聽用戶怎麼說', en: 'Listen to how users say' }, 'Large Conference Registration volunteers need 20--30 people, with Checkin+ now only 10 people is enough! 1/3 Human save it!': { zhtw: '大型會議報到志工都需要20 - 30 人,有了 Checkin+ 現在只要 10個人就夠了!人力節省 1/3 呢!', en: 'Large Conference Registration volunteers need 20--30 people, with Checkin+ now only 10 people is enough! 1/3 Human save it!' }, '- xxxx event hoster': { zhtw: '- xxxx 活動主辦人', en: '- xxxx event hoster' }, 'After the event, always take a long time to sort out the questionnaire and lists After Checkin+, faster analysis was again accurate marketing': { zhtw: '活動結束後,總是要花很長時間整理問卷和名單,用 Checkin+ 後,可以更快分析與會者,再次精準行銷', en: 'After the event, always take a long time to sort out the questionnaire and lists After Checkin+, faster analysis was again accurate marketing' }, '- xxxx Marketing Manager': { zhtw: '- xxxx 行銷經理', en: '- xxxx Marketing Manager' }, 'Participate in activities always stuck in the door line, automatic check-in system can quickly allow members Admission to feel very convenient': { zhtw: '參加活動總是卡在門口排隊,自動簽到系統可以快速讓會員入場,覺得相當方便', en: 'Participate in activities always stuck in the door line, automatic check-in system can quickly allow members Admission to feel very convenient' }, '- xxxx event participants': { zhtw: '- xxxx 活動參加者', en: '- xxxx event participants' }, // footer 'Faithtech Co., Ltd.': { zhtw: '誠義資訊有限公司', en: 'Faithtech Co., Ltd.' }, 'Tel:': { zhtw: '電話:', en: 'Tel:' }, 'Email:': { zhtw: '信箱:', en: 'Email:' }, 'Add:': { zhtw: '地址:', en: 'Add:' }, '10658 6F., No.153, Sec. 3, Xinyi Rd., Da’an Dist., Taipei City 106, Taiwan (R.O.C.)': { zhtw: '10658 台北市大安區信義路三段153號6樓', en: '10658 6F., No.153, Sec. 3, Xinyi Rd., Da’an Dist., Taipei City 106, Taiwan (R.O.C.)' }, // 預約表單 "Hello, please help us fill in the form and we'll contact you as soon as possible, thank you!": { zhtw: '您好,請協助我們填寫表單,我們會盡快和您聯絡,謝謝!', en: "Hello, please help us fill in the form and we'll contact you as soon as possible, thank you!" }, 'Full name': { zhtw: '您的大名', en: 'Full name' }, 'Phone': { zhtw: '聯絡電話', en: 'Phone' }, 'Email': { zhtw: '聯絡信箱', en: 'Email' }, 'Event name': { zhtw: '活動名稱', en: 'Event name' }, 'Event time': { zhtw: '活動時間', en: 'Event time' }, 'From': { zhtw: '從', en: 'From' }, 'To': { zhtw: '到', en: 'To' }, 'Y': { zhtw: '年', en: 'Y' }, 'M': { zhtw: '月', en: 'M' }, 'D': { zhtw: '日', en: 'D' }, 'Event address': { zhtw: '活動地點', en: 'Event address' }, 'Estimated number of activities': { zhtw: '預估活動人數', en: 'Estimated number of activities' }, 'other': { zhtw: '其他', en: 'other' }, // form notice 'Form has been sent': { zhtw: '表單已送出', en: 'Form has been sent' }, "Thank you for your patience to fill, and we'll contact you as soon as possible! Thank you!": { zhtw: '表感謝您耐心填寫,我們會盡快和您聯絡!謝謝!', en: "Thank you for your patience to fill, and we'll contact you as soon as possible! Thank you!" }, 'OK': { zhtw: '確定', en: 'OK' }, 'Woops!': { zhtw: '出了一些問題!', en: 'Woops!' }, 'Sorry,something has gone wrong, you may want to send a letter to [email protected] We will contact you as soon as possible! Thank you!': { zhtw: '抱歉,出了一些問題,您可以先寄信到 [email protected] 我們會盡快和您聯絡!謝謝!', en:'Sorry, something has gone wrong, you may want to send a letter to [email protected] We will contact you as soon as possible! Thank you!' }, }
修改公司名稱 新增“股份”
source/js/jquery.translate.text.js
修改公司名稱
<ide><path>ource/js/jquery.translate.text.js <ide> <ide> // footer <ide> 'Faithtech Co., Ltd.': { <del> zhtw: '誠義資訊有限公司', <add> zhtw: '誠義資訊股份有限公司', <ide> en: 'Faithtech Co., Ltd.' <ide> }, <ide> 'Tel:': {
Java
apache-2.0
74f6261f5ea2db9fd06d1db227285ea40710e94a
0
qtproject/qtqa-gerrit,gerrit-review/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.notedb; import static com.google.common.base.Preconditions.checkArgument; import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.jgit.lib.Config; /** * Implement NoteDb migration stages using {@code gerrit.config}. * * <p>This class controls the state of the migration according to options in {@code gerrit.config}. * In general, any changes to these options should only be made by adventurous administrators, who * know what they're doing, on non-production data, for the purposes of testing the NoteDb * implementation. Changing options quite likely requires re-running {@code RebuildNoteDb}. For * these reasons, the options remain undocumented. */ @Singleton public class ConfigNotesMigration extends NotesMigration { public static class Module extends AbstractModule { @Override public void configure() { bind(NotesMigration.class).to(ConfigNotesMigration.class); } } public static final String SECTION_NOTE_DB = "noteDb"; private static final String DISABLE_REVIEW_DB = "disableReviewDb"; private static final String FUSE_UPDATES = "fuseUpdates"; private static final String PRIMARY_STORAGE = "primaryStorage"; private static final String READ = "read"; private static final String SEQUENCE = "sequence"; private static final String WRITE = "write"; public static Config allEnabledConfig() { Config cfg = new Config(); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), WRITE, true); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), READ, true); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), SEQUENCE, true); cfg.setString(SECTION_NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.NOTE_DB.name()); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), DISABLE_REVIEW_DB, true); // TODO(dborowitz): Set to true when FileRepository supports it. cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), FUSE_UPDATES, false); return cfg; } private final boolean writeChanges; private final boolean readChanges; private final boolean readChangeSequence; private final PrimaryStorage changePrimaryStorage; private final boolean disableChangeReviewDb; private final boolean fuseUpdates; @Inject public ConfigNotesMigration(@GerritServerConfig Config cfg) { writeChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), WRITE, false); readChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), READ, false); // Reading change sequence numbers from NoteDb is not the default even if // reading changes themselves is. Once this is enabled, it's not easy to // undo: ReviewDb might hand out numbers that have already been assigned by // NoteDb. This decision for the default may be reevaluated later. readChangeSequence = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), SEQUENCE, false); changePrimaryStorage = cfg.getEnum(SECTION_NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.REVIEW_DB); disableChangeReviewDb = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), DISABLE_REVIEW_DB, false); fuseUpdates = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), FUSE_UPDATES, false); checkArgument( !(disableChangeReviewDb && changePrimaryStorage != PrimaryStorage.NOTE_DB), "cannot disable ReviewDb for changes if default change primary storage is ReviewDb"); } @Override public boolean rawWriteChangesSetting() { return writeChanges; } @Override public boolean readChanges() { return readChanges; } @Override public boolean readChangeSequence() { return readChangeSequence; } @Override public PrimaryStorage changePrimaryStorage() { return changePrimaryStorage; } @Override public boolean disableChangeReviewDb() { return disableChangeReviewDb; } @Override public boolean fuseUpdates() { return fuseUpdates; } }
gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.notedb; import static com.google.common.base.Preconditions.checkArgument; import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES; import com.google.common.collect.ImmutableSet; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.Set; import org.eclipse.jgit.lib.Config; /** * Implement NoteDb migration stages using {@code gerrit.config}. * * <p>This class controls the state of the migration according to options in {@code gerrit.config}. * In general, any changes to these options should only be made by adventurous administrators, who * know what they're doing, on non-production data, for the purposes of testing the NoteDb * implementation. Changing options quite likely requires re-running {@code RebuildNoteDb}. For * these reasons, the options remain undocumented. */ @Singleton public class ConfigNotesMigration extends NotesMigration { public static class Module extends AbstractModule { @Override public void configure() { bind(NotesMigration.class).to(ConfigNotesMigration.class); } } public static final String SECTION_NOTE_DB = "noteDb"; // All of these names must be reflected in the allowed set in checkConfig. private static final String DISABLE_REVIEW_DB = "disableReviewDb"; private static final String FUSE_UPDATES = "fuseUpdates"; private static final String PRIMARY_STORAGE = "primaryStorage"; private static final String READ = "read"; private static final String SEQUENCE = "sequence"; private static final String WRITE = "write"; private static void checkConfig(Config cfg) { Set<String> keys = ImmutableSet.of(CHANGES.key()); Set<String> allowed = ImmutableSet.of( DISABLE_REVIEW_DB.toLowerCase(), PRIMARY_STORAGE.toLowerCase(), READ.toLowerCase(), WRITE.toLowerCase(), SEQUENCE.toLowerCase()); for (String t : cfg.getSubsections(SECTION_NOTE_DB)) { checkArgument(keys.contains(t.toLowerCase()), "invalid NoteDb table: %s", t); for (String key : cfg.getNames(SECTION_NOTE_DB, t)) { checkArgument(allowed.contains(key.toLowerCase()), "invalid NoteDb key: %s.%s", t, key); } } } public static Config allEnabledConfig() { Config cfg = new Config(); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), WRITE, true); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), READ, true); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), SEQUENCE, true); cfg.setString(SECTION_NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.NOTE_DB.name()); cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), DISABLE_REVIEW_DB, true); // TODO(dborowitz): Set to true when FileRepository supports it. cfg.setBoolean(SECTION_NOTE_DB, CHANGES.key(), FUSE_UPDATES, false); return cfg; } private final boolean writeChanges; private final boolean readChanges; private final boolean readChangeSequence; private final PrimaryStorage changePrimaryStorage; private final boolean disableChangeReviewDb; private final boolean fuseUpdates; @Inject public ConfigNotesMigration(@GerritServerConfig Config cfg) { checkConfig(cfg); writeChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), WRITE, false); readChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), READ, false); // Reading change sequence numbers from NoteDb is not the default even if // reading changes themselves is. Once this is enabled, it's not easy to // undo: ReviewDb might hand out numbers that have already been assigned by // NoteDb. This decision for the default may be reevaluated later. readChangeSequence = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), SEQUENCE, false); changePrimaryStorage = cfg.getEnum(SECTION_NOTE_DB, CHANGES.key(), PRIMARY_STORAGE, PrimaryStorage.REVIEW_DB); disableChangeReviewDb = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), DISABLE_REVIEW_DB, false); fuseUpdates = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), FUSE_UPDATES, false); checkArgument( !(disableChangeReviewDb && changePrimaryStorage != PrimaryStorage.NOTE_DB), "cannot disable ReviewDb for changes if default change primary storage is ReviewDb"); } @Override public boolean rawWriteChangesSetting() { return writeChanges; } @Override public boolean readChanges() { return readChanges; } @Override public boolean readChangeSequence() { return readChangeSequence; } @Override public PrimaryStorage changePrimaryStorage() { return changePrimaryStorage; } @Override public boolean disableChangeReviewDb() { return disableChangeReviewDb; } @Override public boolean fuseUpdates() { return fuseUpdates; } }
ConfigNotesMigration: Remove config sanity check Everywhere else in Gerrit, we don't bother trying to check configs for typos, we just depend on admins to set the right value. In this case, somehow I forgot to add a new config option to the checkConfig method, despite adding a warning after I had already made that mistake twice. This check is clearly not buying us anything, so ditch it. Change-Id: I7201856b6b2651ffc71f26c5409ef7255bdda331
gerrit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java
ConfigNotesMigration: Remove config sanity check
<ide><path>errit-server/src/main/java/com/google/gerrit/server/notedb/ConfigNotesMigration.java <ide> import static com.google.common.base.Preconditions.checkArgument; <ide> import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES; <ide> <del>import com.google.common.collect.ImmutableSet; <ide> import com.google.gerrit.server.config.GerritServerConfig; <ide> import com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage; <ide> import com.google.inject.AbstractModule; <ide> import com.google.inject.Inject; <ide> import com.google.inject.Singleton; <del>import java.util.Set; <ide> import org.eclipse.jgit.lib.Config; <ide> <ide> /** <ide> <ide> public static final String SECTION_NOTE_DB = "noteDb"; <ide> <del> // All of these names must be reflected in the allowed set in checkConfig. <ide> private static final String DISABLE_REVIEW_DB = "disableReviewDb"; <ide> private static final String FUSE_UPDATES = "fuseUpdates"; <ide> private static final String PRIMARY_STORAGE = "primaryStorage"; <ide> private static final String READ = "read"; <ide> private static final String SEQUENCE = "sequence"; <ide> private static final String WRITE = "write"; <del> <del> private static void checkConfig(Config cfg) { <del> Set<String> keys = ImmutableSet.of(CHANGES.key()); <del> Set<String> allowed = <del> ImmutableSet.of( <del> DISABLE_REVIEW_DB.toLowerCase(), <del> PRIMARY_STORAGE.toLowerCase(), <del> READ.toLowerCase(), <del> WRITE.toLowerCase(), <del> SEQUENCE.toLowerCase()); <del> for (String t : cfg.getSubsections(SECTION_NOTE_DB)) { <del> checkArgument(keys.contains(t.toLowerCase()), "invalid NoteDb table: %s", t); <del> for (String key : cfg.getNames(SECTION_NOTE_DB, t)) { <del> checkArgument(allowed.contains(key.toLowerCase()), "invalid NoteDb key: %s.%s", t, key); <del> } <del> } <del> } <ide> <ide> public static Config allEnabledConfig() { <ide> Config cfg = new Config(); <ide> <ide> @Inject <ide> public ConfigNotesMigration(@GerritServerConfig Config cfg) { <del> checkConfig(cfg); <del> <ide> writeChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), WRITE, false); <ide> readChanges = cfg.getBoolean(SECTION_NOTE_DB, CHANGES.key(), READ, false); <ide>
Java
apache-2.0
8f28737e0b69ad7e9ceb1461fecfbb646a7fade0
0
au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-ResearchVocabularies-Toolkit,au-research/ANDS-Vocabs-Toolkit,au-research/ANDS-Vocabs-Toolkit,au-research/ANDS-Vocabs-Toolkit
package au.org.ands.vocabs.toolkit.db.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * Task model class. */ @Entity @Table(name = "task") @NamedQuery( name = Task.GET_ALL_TASKS, query = "SELECT t FROM Task t") @XmlRootElement public class Task { /** Name of getAllTasks query. */ public static final String GET_ALL_TASKS = "getAllTasks"; /** id. */ private Integer id; /** status. */ private String status; /** type. */ private String type; /** params. */ private String params; /** data. */ private String data; /** response. */ private String response; /** vocabularyId. */ private Integer vocabularyId; /** versionId. */ private Integer versionId; /** Get the id. * @return The id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } /** Set the id. * @param anId the id */ public void setId(final Integer anId) { id = anId; } /** Get the status. * @return The status */ @Column(name = "status", length = 45) public String getStatus() { return status; } /** Set the status. * @param aStatus the status */ public void setStatus(final String aStatus) { status = aStatus; } /** Get the type. * @return The type */ @Column(name = "type", length = 45) public String getType() { return type; } /** Set the type. * @param aType the type */ public void setType(final String aType) { type = aType; } /** Get the params. * @return The params */ @Column(name = "params", length = 255) public String getParams() { return params; } /** Set the params. * @param aParams the params */ public void setParams(final String aParams) { params = aParams; } /** Get the data. * @return The data */ @Column(name = "data", length = 65535) public String getData() { return data; } /** Set the data. * @param aData the data */ public void setData(final String aData) { data = aData; } /** Get the response. * @return The response */ @Column(name = "response", length = 45) public String getResponse() { return response; } /** Set the response. * @param aResponse the response */ public void setResponse(final String aResponse) { response = aResponse; } /** Get the vocabulary id. * @return The vocabulary id */ @Column(name = "vocabulary_id") public Integer getVocabularyId() { return vocabularyId; } /** Set the vocabulary id. * @param aVocabularyId the vocabulary id */ public void setVocabularyId(final Integer aVocabularyId) { vocabularyId = aVocabularyId; } /** Get the version id. * @return The version id */ @Column(name = "version_id") public Integer getVersionId() { return versionId; } /** Set the version id. * @param aVersionId the version id */ public void setVersionId(final Integer aVersionId) { versionId = aVersionId; } }
src/main/java/au/org/ands/vocabs/toolkit/db/model/Task.java
package au.org.ands.vocabs.toolkit.db.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * Task model class. */ @Entity @Table(name = "task") @NamedQuery( name = Task.GET_ALL_TASKS, query = "SELECT t FROM Task t") @XmlRootElement public class Task { /** Name of getAllTasks query. */ public static final String GET_ALL_TASKS = "getAllTasks"; /** id. */ private Integer id; /** status. */ private String status; /** type. */ private String type; /** data. */ private String data; /** response. */ private String response; /** vocabularyId. */ private Integer vocabularyId; /** versionId. */ private Integer versionId; /** Get the id. * @return The id */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } /** Set the id. * @param anId the id */ public void setId(final Integer anId) { id = anId; } /** Get the status. * @return The status */ @Column(name = "status", length = 45) public String getStatus() { return status; } /** Set the status. * @param aStatus the status */ public void setStatus(final String aStatus) { status = aStatus; } /** Get the type. * @return The type */ @Column(name = "type", length = 45) public String getType() { return type; } /** Set the type. * @param aType the type */ public void setType(final String aType) { type = aType; } /** Get the data. * @return The data */ @Column(name = "data", length = 65535) public String getData() { return data; } /** Set the data. * @param aData the data */ public void setData(final String aData) { data = aData; } /** Get the response. * @return The response */ @Column(name = "response", length = 45) public String getResponse() { return response; } /** Set the response. * @param aResponse the response */ public void setResponse(final String aResponse) { response = aResponse; } /** Get the vocabulary id. * @return The vocabulary id */ @Column(name = "vocabulary_id") public Integer getVocabularyId() { return vocabularyId; } /** Set the vocabulary id. * @param aVocabularyId the vocabulary id */ public void setVocabularyId(final Integer aVocabularyId) { vocabularyId = aVocabularyId; } /** Get the version id. * @return The version id */ @Column(name = "version_id") public Integer getVersionId() { return versionId; } /** Set the version id. * @param aVersionId the version id */ public void setVersionId(final Integer aVersionId) { versionId = aVersionId; } }
Add params to Task
src/main/java/au/org/ands/vocabs/toolkit/db/model/Task.java
Add params to Task
<ide><path>rc/main/java/au/org/ands/vocabs/toolkit/db/model/Task.java <ide> private String status; <ide> /** type. */ <ide> private String type; <add> /** params. */ <add> private String params; <ide> /** data. */ <ide> private String data; <ide> /** response. */ <ide> */ <ide> public void setType(final String aType) { <ide> type = aType; <add> } <add> <add> /** Get the params. <add> * @return The params <add> */ <add> @Column(name = "params", length = 255) <add> public String getParams() { <add> return params; <add> } <add> <add> /** Set the params. <add> * @param aParams the params <add> */ <add> public void setParams(final String aParams) { <add> params = aParams; <ide> } <ide> <ide> /** Get the data.
Java
mit
3b75386366f96e267d2e5eff48ea9dacfba871fb
0
MarquisLP/WorldScribe,MarquisLP/World-Scribe
package com.averi.worldscribe.utilities; import android.content.Context; import android.os.Environment; import com.averi.worldscribe.Category; import com.averi.worldscribe.R; import java.io.File; /** * Created by mark on 14/06/16. */ public class FileRetriever { public static final String APP_DIRECTORY_NAME = "WorldScribe"; public static File getAppDirectory() { return new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY_NAME); } public static File getWorldDirectory(String worldName) { return new File(getAppDirectory(), worldName); } public static File getCategoryDirectory(Context context, String worldName, Category category) { return new File(getWorldDirectory(worldName), category.pluralName(context)); } public static File getArticleDirectory(Context context, String worldName, Category category, String articleName) { return new File(getCategoryDirectory(context, worldName, category), articleName); } public static File getArticleFile(Context context, String worldName, Category category, String articleName, String fileName) { return new File(getArticleDirectory(context, worldName, category, articleName), fileName); } public static File getConnectionsDirectory(Context context, String worldName, Category category, String articleName) { return new File(getArticleDirectory(context, worldName, category, articleName), context.getResources().getString(R.string.connectionsText)); } public static File getConnectionCategoryDirectory(Context context, String worldName, Category category, String articleName, Category connectionCategory) { return new File(getConnectionsDirectory(context, worldName, category, articleName), connectionCategory.pluralName(context)); } }
app/src/main/java/com/averi/worldscribe/utilities/FileRetriever.java
package com.averi.worldscribe.utilities; import android.content.Context; import android.os.Environment; import com.averi.worldscribe.Category; import com.averi.worldscribe.R; import java.io.File; /** * Created by mark on 14/06/16. */ public class FileRetriever { public static final String APP_DIRECTORY_NAME = "WorldScribe"; public static File getAppDirectory() { return new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY_NAME); } public static File getWorldDirectory(String worldName) { return new File(getAppDirectory(), worldName); } public static File getCategoryDirectory(Context context, String worldName, Category category) { return new File(getWorldDirectory(worldName), category.pluralName(context)); } public static File getArticleDirectory(Context context, String worldName, Category category, String articleName) { return new File(getCategoryDirectory(context, worldName, category), articleName); } public static File getConnectionsDirectory(Context context, String worldName, Category category, String articleName) { return new File(getArticleDirectory(context, worldName, category, articleName), context.getResources().getString(R.string.connectionsText)); } public static File getConnectionCategoryDirectory(Context context, String worldName, Category category, String articleName, Category connectionCategory) { return new File(getConnectionsDirectory(context, worldName, category, articleName), connectionCategory.pluralName(context)); } }
Add getArticleFile to FileRetriever
app/src/main/java/com/averi/worldscribe/utilities/FileRetriever.java
Add getArticleFile to FileRetriever
<ide><path>pp/src/main/java/com/averi/worldscribe/utilities/FileRetriever.java <ide> return new File(getCategoryDirectory(context, worldName, category), articleName); <ide> } <ide> <add> public static File getArticleFile(Context context, String worldName, Category category, <add> String articleName, String fileName) { <add> return new File(getArticleDirectory(context, worldName, category, articleName), <add> fileName); <add> } <add> <ide> public static File getConnectionsDirectory(Context context, String worldName, Category category, <ide> String articleName) { <ide> return new File(getArticleDirectory(context, worldName, category, articleName),
Java
mit
656023160e64746fb9157d771b13f0c3cd1aa0bb
0
SpongePowered/SpongeForge,SpongePowered/SpongeForge
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.forge; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.world.DimensionType; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.FMLLog; import org.spongepowered.api.Sponge; import org.spongepowered.api.world.WorldArchetype; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.interfaces.world.IMixinWorldInfo; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.interfaces.world.IMixinWorldSettings; import org.spongepowered.common.world.WorldManager; import org.spongepowered.mod.util.StaticMixinForgeHelper; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * This mixin redirects all logic in Forge to our WorldManager. */ @Mixin(value = DimensionManager.class, remap = false) public abstract class MixinDimensionManager { @Shadow static Multiset<Integer> leakedWorlds = HashMultiset.create(); @Overwrite public static int[] getDimensions(DimensionType type) { return WorldManager.getRegisteredDimensionIdsFor(type); } @Overwrite public static void init() { WorldManager.registerVanillaTypesAndDimensions(); } @Overwrite public static void registerDimension(int id, DimensionType type) { WorldManager.registerDimension(id, type); } @Overwrite public static void unregisterDimension(int id) { WorldManager.unregisterDimension(id); } @Overwrite public static boolean isDimensionRegistered(int dim) { return WorldManager.isDimensionRegistered(dim); } @Overwrite public static DimensionType getProviderType(int dim) { return WorldManager.getDimensionType(dim).orElse(null); } @Overwrite public static WorldProvider getProvider(int dim) { final Optional<WorldServer> optWorldServer = WorldManager.getWorldByDimensionId(dim); if (optWorldServer.isPresent()) { return optWorldServer.get().provider; } SpongeImpl.getLogger().error("Attempt made to get a provider for dimension id [{}] but it has no provider!"); throw new RuntimeException(); } /** * Gets loaded dimension ids * @param check Check for leaked worlds * @return An array of loaded dimension ids */ @Overwrite public static Integer[] getIDs(boolean check) { if (check) { final List<WorldServer> candidateLeakedWorlds = new ArrayList<>(WorldManager.getWeakWorldMap().values()); candidateLeakedWorlds.removeAll(WorldManager.getWorlds()); leakedWorlds .addAll(candidateLeakedWorlds.stream().map(System::identityHashCode).collect(Collectors.toList())); for (WorldServer worldServer : WorldManager.getWorlds()) { final int hashCode = System.identityHashCode(worldServer); final int leakCount = leakedWorlds.count(hashCode); // Log every 5 loops if (leakCount > 0 && leakCount % 5 == 0) { SpongeImpl.getLogger().warn("World [{}] (DIM{}) (HASH: {}) may have leaked. Encountered [{}] times", worldServer.getWorldInfo() .getWorldName(), ((IMixinWorldServer) worldServer).getDimensionId(), hashCode, leakCount); } } } return getIDs(); } @Overwrite public static Integer[] getIDs() { final int[] spongeDimIds = WorldManager.getLoadedWorldDimensionIds(); Integer[] forgeDimIds = new Integer[spongeDimIds.length]; for (int i = 0; i < spongeDimIds.length; i++) { forgeDimIds[i] = spongeDimIds[i]; } return forgeDimIds; } @Overwrite public static void setWorld(int id, WorldServer world, MinecraftServer server) { if (world != null) { WorldManager.forceAddWorld(id, world); server.worldTickTimes.put(id, new long[100]); FMLLog.info("Loading dimension %d (%s) (%s)", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer()); } else { WorldManager.unloadWorld(WorldManager.getWorldByDimensionId(id).orElseThrow(() -> new RuntimeException("Attempt made to unload a " + "world with dimension id [" + id + "].")), false); server.worldTickTimes.remove(id); } WorldManager.reorderWorldsVanillaFirst(); } /** * @author Zidane - June 2nd, 2016 * @reason Forge's initDimension is very different from Sponge's multi-world. We basically rig it into our system so mods work. * @param dim The dimension to load */ @Overwrite public static void initDimension(int dim) { // World is already loaded, bail if (WorldManager.getWorldByDimensionId(dim).isPresent()) { return; } if (dim == 0) { throw new RuntimeException("Attempt made to initialize overworld!"); } WorldManager.getWorldByDimensionId(0).orElseThrow(() -> new RuntimeException("Attempt made to initialize " + "dimension before overworld is loaded!")); DimensionType dimensionType = WorldManager.getDimensionType(dim).orElse(null); if (dimensionType == null) { SpongeImpl.getLogger().warn("Attempt made to initialize dimension id {} which isn't registered!" + ", falling back to overworld.", dim); return; } final WorldProvider provider = dimensionType.createDimension(); // make sure to set the dimension id to avoid getting a null save folder provider.setDimension(dim); String worldFolder = WorldManager.getWorldFolderByDimensionId(dim).orElse(provider.getSaveFolder()); WorldProperties properties = WorldManager.getWorldProperties(worldFolder).orElse(null); final Path worldPath = WorldManager.getCurrentSavesDirectory().get().resolve(worldFolder); if (properties == null || !Files.isDirectory(worldPath)) { if (properties != null) { WorldManager.unregisterWorldProperties(properties, false); } String modId = StaticMixinForgeHelper.getModIdFromClass(provider.getClass()); WorldArchetype archetype = Sponge.getRegistry().getType(WorldArchetype.class, modId + ":" + dimensionType.getName().toLowerCase()).orElse(null); if (archetype == null) { final WorldArchetype.Builder builder = WorldArchetype.builder() .dimension((org.spongepowered.api.world.DimensionType) (Object) dimensionType) .keepsSpawnLoaded(dimensionType.shouldLoadSpawn()); archetype = builder.build(modId + ":" + dimensionType.getName().toLowerCase(), dimensionType.getName()); } IMixinWorldSettings worldSettings = (IMixinWorldSettings) archetype; worldSettings.setDimensionType((org.spongepowered.api.world.DimensionType) (Object) dimensionType); worldSettings.setLoadOnStartup(false); properties = WorldManager.createWorldProperties(worldFolder, archetype, dim); ((IMixinWorldInfo) properties).setDimensionId(dim); ((IMixinWorldInfo) properties).setIsMod(true); } if (!properties.isEnabled()) { return; } Optional<WorldServer> optWorld = WorldManager.loadWorld(properties); if (!optWorld.isPresent()) { SpongeImpl.getLogger().error("Could not load world [{}]!", properties.getWorldName()); } } @Overwrite public static WorldServer getWorld(int id) { return WorldManager.getWorldByDimensionId(id).orElse(null); } @Overwrite public static WorldServer[] getWorlds() { final Collection<WorldServer> worlds = WorldManager.getWorlds(); return worlds.toArray(new WorldServer[worlds.size()]); } @Overwrite public static Integer[] getStaticDimensionIDs() { final int[] spongeDimIds = WorldManager.getRegisteredDimensionIds(); Integer[] forgeDimIds = new Integer[spongeDimIds.length]; for (int i = 0; i < spongeDimIds.length; i++) { forgeDimIds[i] = spongeDimIds[i]; } return forgeDimIds; } @Overwrite public static WorldProvider createProviderFor(int dim) { final DimensionType dimensionType = WorldManager.getDimensionType(dim).orElseThrow(() -> new RuntimeException("Attempt to create " + "provider for dimension id [" + dim + "] failed because it has not been registered!")); try { final WorldProvider provider = dimensionType.createDimension(); provider.setDimension(dim); return provider; } catch (Exception e) { throw new RuntimeException("Failed to create provider for dimension id [" + dim + "]!"); } } @Overwrite public static void unloadWorld(int id) { WorldManager.getWorldByDimensionId(id).ifPresent(WorldManager::queueWorldToUnload); } @Overwrite public static void unloadWorlds(Hashtable<Integer, long[]> worldTickTimes) { WorldManager.unloadQueuedWorlds(); } @Overwrite public static int getNextFreeDimId() { return WorldManager.getNextFreeDimensionId(); } @Overwrite public static NBTTagCompound saveDimensionDataMap() { return WorldManager.saveDimensionDataMap(); } @Overwrite public static void loadDimensionDataMap(NBTTagCompound compoundTag) { WorldManager.loadDimensionDataMap(compoundTag); } @Overwrite public static File getCurrentSaveRootDirectory() { final Optional<Path> optCurrentSavesDir = WorldManager.getCurrentSavesDirectory(); return optCurrentSavesDir.isPresent() ? optCurrentSavesDir.get().toFile() : null; } }
src/main/java/org/spongepowered/mod/mixin/core/forge/MixinDimensionManager.java
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.forge; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.world.DimensionType; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.FMLLog; import org.spongepowered.api.Sponge; import org.spongepowered.api.world.WorldArchetype; import org.spongepowered.api.world.storage.WorldProperties; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.common.SpongeImpl; import org.spongepowered.common.interfaces.world.IMixinWorldInfo; import org.spongepowered.common.interfaces.world.IMixinWorldServer; import org.spongepowered.common.interfaces.world.IMixinWorldSettings; import org.spongepowered.common.world.WorldManager; import org.spongepowered.mod.util.StaticMixinForgeHelper; import java.io.File; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * This mixin redirects all logic in Forge to our WorldManager. */ @Mixin(value = DimensionManager.class, remap = false) public abstract class MixinDimensionManager { @Shadow static Multiset<Integer> leakedWorlds = HashMultiset.create(); @Overwrite public static int[] getDimensions(DimensionType type) { return WorldManager.getRegisteredDimensionIdsFor(type); } @Overwrite public static void init() { WorldManager.registerVanillaTypesAndDimensions(); } @Overwrite public static void registerDimension(int id, DimensionType type) { WorldManager.registerDimension(id, type); } @Overwrite public static void unregisterDimension(int id) { WorldManager.unregisterDimension(id); } @Overwrite public static boolean isDimensionRegistered(int dim) { return WorldManager.isDimensionRegistered(dim); } @Overwrite public static DimensionType getProviderType(int dim) { return WorldManager.getDimensionType(dim).orElse(null); } @Overwrite public static WorldProvider getProvider(int dim) { final Optional<WorldServer> optWorldServer = WorldManager.getWorldByDimensionId(dim); if (optWorldServer.isPresent()) { return optWorldServer.get().provider; } SpongeImpl.getLogger().error("Attempt made to get a provider for dimension id [{}] but it has no provider!"); throw new RuntimeException(); } /** * Gets loaded dimension ids * @param check Check for leaked worlds * @return An array of loaded dimension ids */ @Overwrite public static Integer[] getIDs(boolean check) { if (check) { final List<WorldServer> candidateLeakedWorlds = new ArrayList<>(WorldManager.getWeakWorldMap().values()); candidateLeakedWorlds.removeAll(WorldManager.getWorlds()); leakedWorlds .addAll(candidateLeakedWorlds.stream().map(System::identityHashCode).collect(Collectors.toList())); for (WorldServer worldServer : WorldManager.getWorlds()) { final int hashCode = System.identityHashCode(worldServer); final int leakCount = leakedWorlds.count(hashCode); // Log every 5 loops if (leakCount > 0 && leakCount % 5 == 0) { SpongeImpl.getLogger().warn("World [{}] (DIM{}) (HASH: {}) may have leaked. Encountered [{}] times", worldServer.getWorldInfo() .getWorldName(), ((IMixinWorldServer) worldServer).getDimensionId(), hashCode, leakCount); } } } return getIDs(); } @Overwrite public static Integer[] getIDs() { final int[] spongeDimIds = WorldManager.getLoadedWorldDimensionIds(); Integer[] forgeDimIds = new Integer[spongeDimIds.length]; for (int i = 0; i < spongeDimIds.length; i++) { forgeDimIds[i] = spongeDimIds[i]; } return forgeDimIds; } @Overwrite public static void setWorld(int id, WorldServer world, MinecraftServer server) { if (world != null) { WorldManager.forceAddWorld(id, world); FMLLog.info("Loading dimension %d (%s) (%s)", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer()); } else { WorldManager.unloadWorld(WorldManager.getWorldByDimensionId(id).orElseThrow(() -> new RuntimeException("Attempt made to unload a " + "world with dimension id [" + id + "].")), false); } WorldManager.reorderWorldsVanillaFirst(); } /** * @author Zidane - June 2nd, 2016 * @reason Forge's initDimension is very different from Sponge's multi-world. We basically rig it into our system so mods work. * @param dim The dimension to load */ @Overwrite public static void initDimension(int dim) { // World is already loaded, bail if (WorldManager.getWorldByDimensionId(dim).isPresent()) { return; } if (dim == 0) { throw new RuntimeException("Attempt made to initialize overworld!"); } WorldManager.getWorldByDimensionId(0).orElseThrow(() -> new RuntimeException("Attempt made to initialize " + "dimension before overworld is loaded!")); DimensionType dimensionType = WorldManager.getDimensionType(dim).orElse(null); if (dimensionType == null) { SpongeImpl.getLogger().warn("Attempt made to initialize dimension id {} which isn't registered!" + ", falling back to overworld.", dim); return; } final WorldProvider provider = dimensionType.createDimension(); // make sure to set the dimension id to avoid getting a null save folder provider.setDimension(dim); String worldFolder = WorldManager.getWorldFolderByDimensionId(dim).orElse(provider.getSaveFolder()); WorldProperties properties = WorldManager.getWorldProperties(worldFolder).orElse(null); final Path worldPath = WorldManager.getCurrentSavesDirectory().get().resolve(worldFolder); if (properties == null || !Files.isDirectory(worldPath)) { if (properties != null) { WorldManager.unregisterWorldProperties(properties, false); } String modId = StaticMixinForgeHelper.getModIdFromClass(provider.getClass()); WorldArchetype archetype = Sponge.getRegistry().getType(WorldArchetype.class, modId + ":" + dimensionType.getName().toLowerCase()).orElse(null); if (archetype == null) { final WorldArchetype.Builder builder = WorldArchetype.builder() .dimension((org.spongepowered.api.world.DimensionType) (Object) dimensionType) .keepsSpawnLoaded(dimensionType.shouldLoadSpawn()); archetype = builder.build(modId + ":" + dimensionType.getName().toLowerCase(), dimensionType.getName()); } IMixinWorldSettings worldSettings = (IMixinWorldSettings) archetype; worldSettings.setDimensionType((org.spongepowered.api.world.DimensionType) (Object) dimensionType); worldSettings.setLoadOnStartup(false); properties = WorldManager.createWorldProperties(worldFolder, archetype, dim); ((IMixinWorldInfo) properties).setDimensionId(dim); ((IMixinWorldInfo) properties).setIsMod(true); } if (!properties.isEnabled()) { SpongeImpl.getLogger().warn("World [{}] (DIM{}) is disabled. World will not be loaded...", worldFolder, dim); return; } Optional<WorldServer> optWorld = WorldManager.loadWorld(properties); if (!optWorld.isPresent()) { SpongeImpl.getLogger().error("Could not load world [{}]!", properties.getWorldName()); } } @Overwrite public static WorldServer getWorld(int id) { return WorldManager.getWorldByDimensionId(id).orElse(null); } @Overwrite public static WorldServer[] getWorlds() { final Collection<WorldServer> worlds = WorldManager.getWorlds(); return worlds.toArray(new WorldServer[worlds.size()]); } @Overwrite public static Integer[] getStaticDimensionIDs() { final int[] spongeDimIds = WorldManager.getRegisteredDimensionIds(); Integer[] forgeDimIds = new Integer[spongeDimIds.length]; for (int i = 0; i < spongeDimIds.length; i++) { forgeDimIds[i] = spongeDimIds[i]; } return forgeDimIds; } @Overwrite public static WorldProvider createProviderFor(int dim) { final DimensionType dimensionType = WorldManager.getDimensionType(dim).orElseThrow(() -> new RuntimeException("Attempt to create " + "provider for dimension id [" + dim + "] failed because it has not been registered!")); try { final WorldProvider provider = dimensionType.createDimension(); provider.setDimension(dim); return provider; } catch (Exception e) { throw new RuntimeException("Failed to create provider for dimension id [" + dim + "]!"); } } @Overwrite public static void unloadWorld(int id) { WorldManager.getWorldByDimensionId(id).ifPresent(WorldManager::queueWorldToUnload); } @Overwrite public static void unloadWorlds(Hashtable<Integer, long[]> worldTickTimes) { WorldManager.unloadQueuedWorlds(); } @Overwrite public static int getNextFreeDimId() { return WorldManager.getNextFreeDimensionId(); } @Overwrite public static NBTTagCompound saveDimensionDataMap() { return WorldManager.saveDimensionDataMap(); } @Overwrite public static void loadDimensionDataMap(NBTTagCompound compoundTag) { WorldManager.loadDimensionDataMap(compoundTag); } @Overwrite public static File getCurrentSaveRootDirectory() { final Optional<Path> optCurrentSavesDir = WorldManager.getCurrentSavesDirectory(); return optCurrentSavesDir.isPresent() ? optCurrentSavesDir.get().toFile() : null; } }
Remove world disabled spam. Fixes #1101 * Reset worldTickTime on setWorld.
src/main/java/org/spongepowered/mod/mixin/core/forge/MixinDimensionManager.java
Remove world disabled spam. Fixes #1101
<ide><path>rc/main/java/org/spongepowered/mod/mixin/core/forge/MixinDimensionManager.java <ide> public static void setWorld(int id, WorldServer world, MinecraftServer server) { <ide> if (world != null) { <ide> WorldManager.forceAddWorld(id, world); <add> server.worldTickTimes.put(id, new long[100]); <ide> FMLLog.info("Loading dimension %d (%s) (%s)", id, world.getWorldInfo().getWorldName(), world.getMinecraftServer()); <ide> } else { <ide> WorldManager.unloadWorld(WorldManager.getWorldByDimensionId(id).orElseThrow(() -> new RuntimeException("Attempt made to unload a " <ide> + "world with dimension id [" + id + "].")), false); <add> server.worldTickTimes.remove(id); <ide> } <ide> <ide> WorldManager.reorderWorldsVanillaFirst(); <ide> ((IMixinWorldInfo) properties).setIsMod(true); <ide> } <ide> if (!properties.isEnabled()) { <del> SpongeImpl.getLogger().warn("World [{}] (DIM{}) is disabled. World will not be loaded...", worldFolder, <del> dim); <ide> return; <ide> } <ide>
Java
artistic-2.0
5731c6fbd324083388a8019dcb2c9d2c2e06e457
0
TimePath/commons,TimePath/commons
package com.timepath; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author TimePath */ public class XMLUtils { private static final Logger LOG = Logger.getLogger(XMLUtils.class.getName()); private XMLUtils() { } /** * Attempts to get the last text node by key * * @param root * @param key * @return the text, or null */ public static String get(Node root, String key) { try { List<Node> elements = getElements(root, key); if (elements.size() == 0) return null; Node firstChild = last(elements).getFirstChild(); if (firstChild == null) return null; return firstChild.getNodeValue(); } catch (NullPointerException ignored) { return null; } } /** * Get a list of nodes from the '/' delimited expression * * @param root * @param expression * @return */ public static List<Node> getElements(Node root, String expression) { String[] path = expression.split("/"); List<Node> nodes = new LinkedList<>(); nodes.add(root); for (String part : path) { List<Node> temp = new LinkedList<>(); for (Node scan : nodes) { for (Node node : get(scan, Node.ELEMENT_NODE)) { if (node.getNodeName().equals(part)) { temp.add(node); } } } nodes = temp; } return nodes; } /** * Get direct descendants by type * * @param parent * @param nodeType * @return */ public static List<Node> get(Node parent, short nodeType) { List<Node> list = new LinkedList<>(); if (parent.hasChildNodes()) { NodeList nodes = parent.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { try { Node node = nodes.item(i); if (node.getNodeType() == nodeType) { list.add(node); } } catch (NullPointerException ignored) { // nodes.item() is broken break; } } } return list; } /** * Get the last item in a list, or null */ public static <E> E last(List<E> list) { return ((list == null) || list.isEmpty()) ? null : list.get(list.size() - 1); } /** * Fetch the first root by name from the given stream * * @param is * @param name * @return * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public static Node rootNode(final InputStream is, String name) throws ParserConfigurationException, IOException, SAXException { if (is == null) { throw new IllegalArgumentException("InputStream cannot be null"); } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(is); return getElements(doc, name).get(0); } public static String pprint(Node n) { try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", true); writer.getDomConfig().setParameter("xml-declaration", false); return writer.writeToString(n); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.log(Level.SEVERE, null, e); return String.valueOf(n); } } public static String pprint(Source xmlInput, int indent) { try { StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (IllegalArgumentException | TransformerException e) { LOG.log(Level.SEVERE, null, e); return String.valueOf(xmlInput); } } }
src/main/java/com/timepath/XMLUtils.java
package com.timepath; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author TimePath */ public class XMLUtils { private static final Logger LOG = Logger.getLogger(XMLUtils.class.getName()); private XMLUtils() { } /** * Attempts to get the last text node by key * * @param root * @param key * @return the text, or null */ public static String get(Node root, String key) { try { List<Node> elements = getElements(root, key); if(elements.size() == 0) return null; Node firstChild = last(elements).getFirstChild(); if(firstChild == null) return null; return firstChild.getNodeValue(); } catch (NullPointerException ignored) { return null; } } /** * Get a list of nodes from the '/' delimited expression * * @param root * @param expression * @return */ public static List<Node> getElements(Node root, String expression) { String[] path = expression.split("/"); List<Node> nodes = new LinkedList<>(); nodes.add(root); for (String part : path) { List<Node> temp = new LinkedList<>(); for (Node scan : nodes) { for (Node node : get(scan, Node.ELEMENT_NODE)) { if (node.getNodeName().equals(part)) { temp.add(node); } } } nodes = temp; } return nodes; } /** * Get direct descendants by type * * @param parent * @param nodeType * @return */ public static List<Node> get(Node parent, short nodeType) { List<Node> list = new LinkedList<>(); if (parent.hasChildNodes()) { NodeList nodes = parent.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == nodeType) { list.add(node); } } } return list; } /** * Get the last item in a list, or null */ public static <E> E last(List<E> list) { return ((list == null) || list.isEmpty()) ? null : list.get(list.size() - 1); } /** * Fetch the first root by name from the given stream * * @param is * @param name * @return * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public static Node rootNode(final InputStream is, String name) throws ParserConfigurationException, IOException, SAXException { if (is == null) { throw new IllegalArgumentException("InputStream cannot be null"); } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(is); return getElements(doc, name).get(0); } public static String pprint(Node n) { try { DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", true); writer.getDomConfig().setParameter("xml-declaration", false); return writer.writeToString(n); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOG.log(Level.SEVERE, null, e); return String.valueOf(n); } } public static String pprint(Source xmlInput, int indent) { try { StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (IllegalArgumentException | TransformerException e) { LOG.log(Level.SEVERE, null, e); return String.valueOf(xmlInput); } } }
Safeguard badly behaved XML method
src/main/java/com/timepath/XMLUtils.java
Safeguard badly behaved XML method
<ide><path>rc/main/java/com/timepath/XMLUtils.java <ide> public static String get(Node root, String key) { <ide> try { <ide> List<Node> elements = getElements(root, key); <del> if(elements.size() == 0) return null; <add> if (elements.size() == 0) return null; <ide> Node firstChild = last(elements).getFirstChild(); <del> if(firstChild == null) return null; <add> if (firstChild == null) return null; <ide> return firstChild.getNodeValue(); <ide> } catch (NullPointerException ignored) { <ide> return null; <ide> if (parent.hasChildNodes()) { <ide> NodeList nodes = parent.getChildNodes(); <ide> for (int i = 0; i < nodes.getLength(); i++) { <del> Node node = nodes.item(i); <del> if (node.getNodeType() == nodeType) { <del> list.add(node); <add> try { <add> Node node = nodes.item(i); <add> if (node.getNodeType() == nodeType) { <add> list.add(node); <add> } <add> } catch (NullPointerException ignored) { <add> // nodes.item() is broken <add> break; <ide> } <ide> } <ide> }
Java
apache-2.0
5955ca1708076a1eac0e7862f5211ce92ee350f6
0
rouazana/james,rouazana/james,chibenwa/james,rouazana/james,rouazana/james,chibenwa/james,aduprat/james,aduprat/james,chibenwa/james,aduprat/james,aduprat/james,chibenwa/james
/**************************************************************** * 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.james.pop3server.netty; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.net.ssl.SSLEngine; import org.apache.commons.logging.Log; import org.apache.james.mailbox.MessageManager; import org.apache.james.pop3server.POP3HandlerConfigurationData; import org.apache.james.pop3server.POP3Session; import org.apache.james.protocols.impl.AbstractSession; import org.jboss.netty.channel.ChannelHandlerContext; /** * {@link POP3Session} implementation which use Netty * */ public class POP3NettySession extends AbstractSession implements POP3Session { private POP3HandlerConfigurationData configData; private Map<String, Object> state = new HashMap<String, Object>(); private int handlerState; private MessageManager mailbox; private NonClosingChannelOutputStream out; public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext) { this(configData, logger, handlerContext, null); } public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext, SSLEngine engine) { super(logger, handlerContext, engine); this.configData = configData; this.out = new NonClosingChannelOutputStream(getChannelHandlerContext().getChannel()); } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#getConfigurationData() */ public POP3HandlerConfigurationData getConfigurationData() { return configData; } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#getHandlerState() */ public int getHandlerState() { return handlerState; } /* * (non-Javadoc) * * @see org.apache.james.api.protocol.TLSSupportedSession#getState() */ public Map<String, Object> getState() { return state; } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#setHandlerState(int) */ public void setHandlerState(int handlerState) { this.handlerState = handlerState; } /* * (non-Javadoc) * * @see org.apache.james.api.protocol.TLSSupportedSession#resetState() */ public void resetState() { state.clear(); setHandlerState(AUTHENTICATION_READY); } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#getUserMailbox() */ public MessageManager getUserMailbox() { return mailbox; } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#setUserMailbox(org.apache.james.imap.mailbox.Mailbox) */ public void setUserMailbox(MessageManager mailbox) { this.mailbox = mailbox; } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#getOutputStream() */ public OutputStream getOutputStream() { return out; } }
pop3server/src/main/java/org/apache/james/pop3server/netty/POP3NettySession.java
/**************************************************************** * 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.james.pop3server.netty; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.net.ssl.SSLEngine; import org.apache.commons.logging.Log; import org.apache.james.mailbox.MessageManager; import org.apache.james.pop3server.POP3HandlerConfigurationData; import org.apache.james.pop3server.POP3Session; import org.apache.james.protocols.impl.AbstractSession; import org.jboss.netty.channel.ChannelHandlerContext; /** * {@link POP3Session} implementation which use Netty * */ public class POP3NettySession extends AbstractSession implements POP3Session { private POP3HandlerConfigurationData configData; private Map<String, Object> state = new HashMap<String, Object>(); private int handlerState; private MessageManager mailbox; public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext) { super(logger, handlerContext); this.configData = configData; } public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext, SSLEngine engine) { super(logger, handlerContext, engine); this.configData = configData; } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#getConfigurationData() */ public POP3HandlerConfigurationData getConfigurationData() { return configData; } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#getHandlerState() */ public int getHandlerState() { return handlerState; } /* * (non-Javadoc) * * @see org.apache.james.api.protocol.TLSSupportedSession#getState() */ public Map<String, Object> getState() { return state; } /* * (non-Javadoc) * * @see org.apache.james.pop3server.POP3Session#setHandlerState(int) */ public void setHandlerState(int handlerState) { this.handlerState = handlerState; } /* * (non-Javadoc) * * @see org.apache.james.api.protocol.TLSSupportedSession#resetState() */ public void resetState() { state.clear(); setHandlerState(AUTHENTICATION_READY); } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#getUserMailbox() */ public MessageManager getUserMailbox() { return mailbox; } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#setUserMailbox(org.apache.james.imap.mailbox.Mailbox) */ public void setUserMailbox(MessageManager mailbox) { this.mailbox = mailbox; } /* * (non-Javadoc) * @see org.apache.james.pop3server.POP3Session#getOutputStream() */ public OutputStream getOutputStream() { return new NonClosingChannelOutputStream(getChannelHandlerContext().getChannel()); } }
Share outputstream on channel per session git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@1035794 13f79535-47bb-0310-9956-ffa450edef68
pop3server/src/main/java/org/apache/james/pop3server/netty/POP3NettySession.java
Share outputstream on channel per session
<ide><path>op3server/src/main/java/org/apache/james/pop3server/netty/POP3NettySession.java <ide> <ide> private MessageManager mailbox; <ide> <add> private NonClosingChannelOutputStream out; <add> <ide> public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext) { <del> super(logger, handlerContext); <del> this.configData = configData; <add> this(configData, logger, handlerContext, null); <ide> } <ide> <ide> <ide> public POP3NettySession(POP3HandlerConfigurationData configData, Log logger, ChannelHandlerContext handlerContext, SSLEngine engine) { <ide> super(logger, handlerContext, engine); <ide> this.configData = configData; <add> this.out = new NonClosingChannelOutputStream(getChannelHandlerContext().getChannel()); <ide> } <ide> <ide> <ide> * @see org.apache.james.pop3server.POP3Session#getOutputStream() <ide> */ <ide> public OutputStream getOutputStream() { <del> return new NonClosingChannelOutputStream(getChannelHandlerContext().getChannel()); <add> return out; <ide> } <ide> <ide> }
Java
apache-2.0
742810777ff005eb6628c9668ae27a7b8d9ff708
0
blackberry/Krackle,awwal/Krackle
/** * Copyright 2014 BlackBerry, Limited. * * 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.blackberry.bdp.krackle.producer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.blackberry.bdp.krackle.Constants; import com.blackberry.bdp.krackle.KafkaError; import com.blackberry.bdp.krackle.MetricRegistrySingleton; import com.blackberry.bdp.krackle.compression.Compressor; import com.blackberry.bdp.krackle.compression.GzipCompressor; import com.blackberry.bdp.krackle.compression.SnappyCompressor; import com.blackberry.bdp.krackle.meta.Broker; import com.blackberry.bdp.krackle.meta.MetaData; import com.blackberry.bdp.krackle.meta.Topic; import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; /** * An implementation of the Kafka 0.8 producer. * * This class acts as a producer of data to a cluster of Kafka brokers. Each * instance only sends data for a single topic, using a single key. If you need * to write to more topics (or using different keys), then instantiate more * instances. * * This producer is asynchonous only. There is no synchronous mode. * * This class was designed to be very light weight. The standard Java client * creates a lot of objects, and therefore causes a lot of garbage collection * that leads to a major slowdown in performance. This client creates ver few * new objects during steady state running, and so avoids most garbage * collection overhead. */ public class Producer { private static final Logger LOG = LoggerFactory.getLogger(Producer.class); private static final Charset UTF8 = Charset.forName("UTF-8"); private ProducerConfiguration conf; private String clientIdString; private byte[] clientIdBytes; private short clientIdLength; private String keyString; private int partitionModifier; private byte[] keyBytes; private int keyLength; private String topicString; private byte[] topicBytes; private short topicLength; // Various configs private short requiredAcks; private int brokerTimeout; private int retries; private int compressionLevel; private int retryBackoffMs; private long topicMetadataRefreshIntervalMs; private long queueBufferingMaxMs; // Store the uncompressed message set that we will be compressing later. private int numBuffers; private BlockingQueue<MessageSetBuffer> freeBuffers = null; private static final Object sharedBufferLock = new Object(); private static BlockingQueue<MessageSetBuffer> sharedBuffers = null; private BlockingQueue<MessageSetBuffer> buffersToSend; // Store the compressed message + headers. // Generally, this needs to be bigger than the messageSetBufferSize // for uncompressed messages (size + key length + topic length + 34?) // For compressed messages, this shouldn't need to be bigger. private int sendBufferSize; // How to compress! Compressor compressor; // We could be using crc in 2 separate blocks, which could cause corruption // with one instance. private CRC32 crcSend = new CRC32(); //private Sender sender = null; private ArrayList<Thread> senderThreads = new ArrayList<>(); private ArrayList<Sender> senders = new ArrayList<>(); private boolean closed = false; private ScheduledExecutorService scheduledExecutor = Executors .newSingleThreadScheduledExecutor(); private MetricRegistry metrics; private Meter mReceived = null; private Meter mReceivedTotal = null; private Meter mSent = null; private Meter mSentTotal = null; private Meter mDroppedQueueFull = null; private Meter mDroppedQueueFullTotal = null; private Meter mDroppedSendFail = null; private Meter mDroppedSendFailTotal = null; private String freeBufferGaugeName; /** * Create a new producer using a given instance of MetricRegistry instead of * the default singleton. * * @param conf * ProducerConfiguration to use * @param clientId * client id to send to the brokers * @param topic * topic to produce on * @param key * key to use for partitioning * @param metrics * MetricRegistry instance to use for metrics. * @throws Exception */ public Producer(ProducerConfiguration conf, String clientId, String topic, String key, MetricRegistry metrics) throws Exception { LOG.info("Creating new producer for topic {}, key {}", topic, key); this.conf = conf; clientId = clientId + "-" + Long.toHexString(Double.doubleToLongBits(Math.random())); LOG.info("Client ID: {}", clientId); this.topicString = topic; this.topicBytes = topic.getBytes(UTF8); this.topicLength = (short) topicBytes.length; this.clientIdString = clientId; this.clientIdBytes = clientId.getBytes(UTF8); this.clientIdLength = (short) clientId.length(); this.keyString = key; this.keyBytes = key.getBytes(UTF8); this.keyLength = keyBytes.length; this.partitionModifier = 0; if (metrics == null) { this.metrics = MetricRegistrySingleton.getInstance().getMetricsRegistry(); MetricRegistrySingleton.getInstance().enableJmx(); MetricRegistrySingleton.getInstance().enableConsole(); } else { this.metrics = metrics; } initializeMetrics(); configure(); // Start a periodic sender to ensure that things get sent from time to // time. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { send(null, 0, 0); } catch (Exception e) { // That's fine. } } }, queueBufferingMaxMs, queueBufferingMaxMs, TimeUnit.MILLISECONDS); // Create the sender objects and threads for (int i = 0; i < conf.getSenderThreads(); i++) { Sender sender = new Sender(); Thread senderThread = new Thread(sender); senderThread.setDaemon(false); LOG.debug("[{}] Creating Sender Thread-{} ({})", topicString, i, senderThread.toString()); senderThread.setName("Sender-Thread-" + i + "-" + senderThread.getId()); senderThread.start(); senderThreads.add(senderThread); senders.add(sender); } // Ensure that if the sender thread ever dies, it is restarted. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { ArrayList<Thread> toRemove = new ArrayList<Thread>(); ArrayList<Thread> toAdd = new ArrayList<Thread>(); for(Thread senderThread : senderThreads) { if (senderThread == null || senderThread.isAlive() == false) { Sender sender = new Sender(); toRemove.add(senderThread); LOG.error("[{}] Sender thread {} clientId {} is dead! Restarting it.", topicString, senderThread.getName(), clientIdString); senderThread = new Thread(sender); senderThread.setDaemon(false); senderThread.setName("Sender-Thread-" + senderThread.getId()); senderThread.start(); toAdd.add(senderThread); } } for(Thread removeThread: toRemove) { senderThreads.remove(removeThread); } for(Thread addThread: toAdd) { senderThreads.add(addThread); } } }, 1, 1, TimeUnit.MINUTES); } private void initializeMetrics() { String name = topicString; mReceived = this.metrics.meter("krackle:producer:topics:" + name + ":messages received"); mReceivedTotal = this.metrics .meter("krackle:producer:total:messages received"); mSent = this.metrics.meter("krackle:producer:topics:" + name + ":messages sent"); mSentTotal = this.metrics.meter("krackle:producer:total:messages sent"); mDroppedQueueFull = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (queue full)"); mDroppedQueueFullTotal = this.metrics .meter("krackle:producer:total:messages dropped (queue full)"); mDroppedSendFail = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (send failure)"); mDroppedSendFailTotal = this.metrics .meter("krackle:producer:total:messages dropped (send failure)"); } private void configure() throws Exception { requiredAcks = conf.getRequestRequiredAcks(); retryBackoffMs = conf.getRetryBackoffMs(); brokerTimeout = conf.getRequestTimeoutMs(); retries = conf.getMessageSendMaxRetries(); sendBufferSize = conf.getSendBufferSize(); topicMetadataRefreshIntervalMs = conf.getTopicMetadataRefreshIntervalMs(); queueBufferingMaxMs = conf.getQueueBufferingMaxMs(); String compressionCodec = conf.getCompressionCodec(); compressionLevel = conf.getCompressionLevel(); int messageBufferSize = conf.getMessageBufferSize(); numBuffers = conf.getNumBuffers(); // Check to see if we're using a shared buffer, or dedicated buffers. if (conf.isUseSharedBuffers()) { synchronized (sharedBufferLock) { if (sharedBuffers == null) { sharedBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { sharedBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } MetricRegistrySingleton .getInstance() .getMetricsRegistry() .register("krackle:producer:shared free buffers", new Gauge<Integer>() { @Override public Integer getValue() { return sharedBuffers.size(); } }); } } freeBuffers = sharedBuffers; } else { freeBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { freeBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } freeBufferGaugeName = "krackle:producer:topics:" + topicString + ":free buffers"; if (MetricRegistrySingleton.getInstance().getMetricsRegistry() .getGauges(new MetricFilter() { @Override public boolean matches(String s, Metric m) { return s.equals(freeBufferGaugeName); } }).size() > 0) { LOG.warn("Gauge already exists for '{}'", freeBufferGaugeName); } else { MetricRegistrySingleton.getInstance().getMetricsRegistry() .register(freeBufferGaugeName, new Gauge<Integer>() { @Override public Integer getValue() { return freeBuffers.size(); } }); } } buffersToSend = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); if (compressionCodec.equals("none")) { compressor = null; } else if (compressionCodec.equals("snappy")) { compressor = new SnappyCompressor(); } else if (compressionCodec.equals("gzip")) { compressor = new GzipCompressor(compressionLevel); } else { throw new Exception("Unknown compression type: " + compressionCodec); } } private int crcPos; private MessageSetBuffer activeMessageSetBuffer = null; private ByteBuffer activeByteBuffer; /** * Add a message to the send queue * * Takes bytes from buffer from start, up to length bytes. * * @param buffer * byte array to read from. * @param offset * location in source to start from. * @param length * length of input data to read. * @throws Exception */ public synchronized void send(byte[] buffer, int offset, int length) throws Exception { if (closed) { LOG.warn("Trying to send data on a closed producer."); return; } if (activeMessageSetBuffer == null) { if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } // null buffer means send what we have if (buffer == null) { if (activeMessageSetBuffer.getBatchSize() > 0) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; } return; } mReceived.mark(); mReceivedTotal.mark(); if (activeMessageSetBuffer.getBuffer().remaining() < length + keyLength + 26) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } activeByteBuffer = activeMessageSetBuffer.getBuffer(); // Offset activeByteBuffer.putLong(0L); // Size of uncompressed message activeByteBuffer.putInt(length + keyLength + 14); crcPos = activeByteBuffer.position(); activeByteBuffer.position(crcPos + 4); // magic number activeByteBuffer.put(Constants.MAGIC_BYTE); // no compression activeByteBuffer.put(Constants.NO_COMPRESSION); activeByteBuffer.putInt(keyLength); // Key length activeByteBuffer.put(keyBytes); // Key activeByteBuffer.putInt(length); // Value length activeByteBuffer.put(buffer, offset, length); // Value crcSend.reset(); crcSend.update(activeMessageSetBuffer.getBytes(), crcPos + 4, length + keyLength + 10); activeByteBuffer.putInt(crcPos, (int) crcSend.getValue()); activeMessageSetBuffer.incrementBatchSize(); } int nextLoadingBuffer; boolean incrementLoadingBufferResult; private String getErrorString(short errorCode) { for (KafkaError e : KafkaError.values()) { if (e.getCode() == errorCode) { return e.getMessage(); } } return null; } public synchronized void close() { LOG.info("Closing producer."); closed = true; buffersToSend.add(activeMessageSetBuffer); activeMessageSetBuffer = null; try { for(Thread senderThread : senderThreads) { senderThread.join(); } } catch (InterruptedException e) { LOG.error("Error shutting down sender and loader threads.", e); } if (conf.isUseSharedBuffers() == false) { MetricRegistrySingleton.getInstance().getMetricsRegistry() .remove(freeBufferGaugeName); } } private class Sender implements Runnable { private MessageSetBuffer buffer; private int lastLatency = 0; private int correlationId = 0; private byte[] toSendBytes; private ByteBuffer toSendBuffer; private int messageSetSizePos; private int messageSizePos; private int messageCompressedSize; private CRC32 crcSendMessage = new CRC32(); private Random rand = new Random(); // Buffer for reading responses from the server. private byte[] responseBytes; private ByteBuffer responseBuffer; private int responseSize; private int responseCorrelationId; private short responseErrorCode; private int retry; private Socket socket; private OutputStream out; private InputStream in; private String clientThreadIdString; private byte[] clientThreadIdBytes; private short clientThreadIdLength; private MetaData metadata; private long lastMetadataRefresh; private int partition; private Broker broker; private String brokerAddress = null; public Sender() { toSendBytes = new byte[sendBufferSize]; toSendBuffer = ByteBuffer.wrap(toSendBytes); // We need this to be big enough to read the length of the first response, // then we can expand it to the appropriate size. responseBytes = new byte[4]; responseBuffer = ByteBuffer.wrap(responseBytes); // Try to do this. If it fails, then we can try again when it's time to // send. try { // In case this fails, we don't want the value to be null; lastMetadataRefresh = System.currentTimeMillis(); updateMetaDataAndConnection(true); } catch (Throwable t) { LOG.warn("Initial load of metadata failed.", t); metadata = null; } } private void updateMetaDataAndConnection(boolean force) throws MissingPartitionsException { LOG.info("{} - Updating metadata", Thread.currentThread().getName()); metadata = MetaData.getMetaData(conf.getMetadataBrokerList(), topicString, clientIdString ); LOG.debug("Metadata: {}", metadata); Topic topic = metadata.getTopic(topicString); if (topic.getNumPartitions() == 0) { throw new MissingPartitionsException(String.format("Topic %s has zero partitions", topicString), null); } if (!force) { //We don't rotate if it's a forced meta-data refresh, as we would have a block in the queue waiting to send if(conf.getPartitionsRotate() == 1) { //rotate sequentially partitionModifier = (partitionModifier + 1) % topic.getNumPartitions(); LOG.info("Metadata and connection refresh called without force, partition modifier is now: {}", partitionModifier); } else if (conf.getPartitionsRotate() == 2) { //pick a random number to increase partitions by partitionModifier = rand.nextInt(topic.getNumPartitions()); } } partition = (Math.abs(keyString.hashCode()) + partitionModifier) % topic.getNumPartitions(); LOG.info("Sending to partition {} of {}", partition, topic.getNumPartitions()); broker = metadata.getBroker(topic.getPartition(partition).getLeader()); // Only reset our connection if the broker has changed, or it's forced String newBrokerAddress = broker.getHost() + ":" + broker.getPort(); if (force || brokerAddress == null || brokerAddress.equals(newBrokerAddress) == false) { brokerAddress = newBrokerAddress; LOG.info("Changing brokers to {}", broker); if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.error("Error closing connection to broker.", e); } } try { socket = new Socket(broker.getHost(), broker.getPort()); socket.setSendBufferSize(conf.getSendBufferSize()); socket.setSoTimeout(conf.getRequestTimeoutMs() + 1000); LOG.info("Connected to {}", socket); in = socket.getInputStream(); out = socket.getOutputStream(); } catch (UnknownHostException e) { LOG.error("Error connecting to broker.", e); } catch (IOException e) { LOG.error("Error connecting to broker.", e); } } lastMetadataRefresh = System.currentTimeMillis(); } // Send accumulated messages protected void sendMessage(MessageSetBuffer messageSetBuffer) { try { // New message, new id correlationId++; /* headers */ // Skip 4 bytes for the size toSendBuffer.position(4); // API key for produce toSendBuffer.putShort(Constants.APIKEY_PRODUCE); // Version toSendBuffer.putShort(Constants.API_VERSION); // Correlation Id toSendBuffer.putInt(correlationId); // Client Id toSendBuffer.putShort(clientIdLength); toSendBuffer.put(clientIdBytes); // Required Acks toSendBuffer.putShort(requiredAcks); // Timeout in ms toSendBuffer.putInt(brokerTimeout); // Number of topics toSendBuffer.putInt(1); // Topic name toSendBuffer.putShort(topicLength); toSendBuffer.put(topicBytes); // Number of partitions toSendBuffer.putInt(1); // Partition toSendBuffer.putInt(partition); if (compressor == null) { // If we 're not compressing, then we can just dump the rest of the // message here. // Message set size toSendBuffer.putInt(messageSetBuffer.getBuffer().position()); // Message set toSendBuffer.put(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position()); } else { // If we are compressing, then do that. // Message set size ? We'll have to do this later. messageSetSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 4); // offset can be anything for produce requests. We'll use 0 toSendBuffer.putLong(0L); // Skip 4 bytes for size, and 4 for crc messageSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 8); toSendBuffer.put(Constants.MAGIC_BYTE); // magic number toSendBuffer.put(compressor.getAttribute()); // Compression goes // here. // Add the key toSendBuffer.putInt(keyLength); toSendBuffer.put(keyBytes); // Compress the value here, into the toSendBuffer try { messageCompressedSize = compressor.compress(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position(), toSendBytes, toSendBuffer.position() + 4); if (messageCompressedSize == -1) { // toSendBytes is too small to hold the compressed data throw new IOException( "Not enough room in the send buffer for the compressed data."); } } catch (IOException e) { LOG.error("Exception while compressing data. (data lost).", e); return; } // Write the size toSendBuffer.putInt(messageCompressedSize); // Update the send buffer position toSendBuffer.position(toSendBuffer.position() + messageCompressedSize); /** Go back and fill in the missing pieces **/ // Message Set Size toSendBuffer.putInt(messageSetSizePos, toSendBuffer.position() - (messageSetSizePos + 4)); // Message Size toSendBuffer.putInt(messageSizePos, toSendBuffer.position() - (messageSizePos + 4)); // Message CRC crcSendMessage.reset(); crcSendMessage.update(toSendBytes, messageSizePos + 8, toSendBuffer.position() - (messageSizePos + 8)); toSendBuffer.putInt(messageSizePos + 4, (int) crcSendMessage.getValue()); } // Fill in the complete message size toSendBuffer.putInt(0, toSendBuffer.position() - 4); // Send it! retry = 0; while (retry <= retries) { try { if (metadata == null || socket == null) { updateMetaDataAndConnection(true); } LOG.debug("[{}] Sender Thread-{} ({}) Sending Block with CorrelationId: {} ClientId: {} Socket: {}", topicString, senderThreads.indexOf(Thread.currentThread()), Thread.currentThread().getId(), correlationId, clientIdString, socket.toString()); // Send request out.write(toSendBytes, 0, toSendBuffer.position()); if (requiredAcks != 0) { // Check response responseBuffer.clear(); in.read(responseBytes, 0, 4); responseSize = responseBuffer.getInt(); if (responseBuffer.capacity() < responseSize) { responseBytes = new byte[responseSize]; responseBuffer = ByteBuffer.wrap(responseBytes); } responseBuffer.clear(); in.read(responseBytes, 0, responseSize); // Response bytes are // - 4 byte correlation id // - 4 bytes for number of topics. This is always 1 in this case. // - 2 bytes for length of topic name. // - topicLength bytes for topic // - 4 bytes for number of partitions. Always 1. // - 4 bytes for partition number (which we already know) // - 2 bytes for error code (That's interesting to us) // - 8 byte offset of the first message (we don't care). // The only things we care about here are the correlation id (must // match) and the error code (so we can throw an exception if it's // not 0) responseCorrelationId = responseBuffer.getInt(); if (responseCorrelationId != correlationId) { throw new Exception("Correlation ID mismatch. Expected " + correlationId + ", got " + responseCorrelationId + " ClientID: " + clientIdString + " Socket: " + socket.toString()); } responseErrorCode = responseBuffer.getShort(18 + topicLength); if (responseErrorCode != KafkaError.NoError.getCode()) { throw new Exception("Got error from broker. Error Code " + responseErrorCode + " (" + getErrorString(responseErrorCode) + ")"); } // Clear the responses, if there is anything else to read while (in.available() > 0) { in.read(responseBytes, 0, responseBytes.length); } } break; } catch (Throwable t) { metadata = null; retry++; if (retry <= retries) { LOG.warn("Request failed. Retrying {} more times for {}.", retries - retry + 1, topicString, t); try { Thread.sleep(retryBackoffMs); } catch (InterruptedException e) { // Do nothing } } else { LOG.error("Request failed. No more retries (data lost) for {}.", topicString, t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } } toSendBuffer.clear(); mSent.mark(messageSetBuffer.getBatchSize()); mSentTotal.mark(messageSetBuffer.getBatchSize()); // Periodic metadata refreshes. if ((topicMetadataRefreshIntervalMs >= 0 && System.currentTimeMillis() - lastMetadataRefresh >= topicMetadataRefreshIntervalMs)) { try { updateMetaDataAndConnection(false); } catch (Throwable t) { LOG.error("Error refreshing metadata.", t); } } } catch (Throwable t) { LOG.error("Unexpected exception: {}", t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } @Override public void run() { float sendStart = 0; this.clientThreadIdString = clientIdString + "-" + Thread.currentThread().getId(); this.clientThreadIdBytes = clientThreadIdString.getBytes(UTF8); this.clientThreadIdLength = (short) clientThreadIdString.length(); LOG.debug("Starting Run Of Sender Thread: " + Thread.currentThread().getName()+ "-"+ Thread.currentThread().getId()); String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread()) + ":blockTransmitTime - ms"; MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName, new Gauge<Integer>() { @Override public Integer getValue() { return lastLatency; } }); while (true) { try { if (closed && buffersToSend.isEmpty()) { break; } try { buffer = buffersToSend.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Interrupted polling for a new buffer.", e); continue; } if (buffer == null) { continue; } sendStart = System.currentTimeMillis(); sendMessage(buffer); buffer.clear(); freeBuffers.add(buffer); lastLatency = (int)(System.currentTimeMillis() - sendStart); } catch (Throwable t) { LOG.error("Unexpected error", t); } } LOG.debug("Finishing Run Of Sender Thread: " + Thread.currentThread().getId()); } } }
src/main/java/com/blackberry/bdp/krackle/producer/Producer.java
/** * Copyright 2014 BlackBerry, Limited. * * 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.blackberry.bdp.krackle.producer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.zip.CRC32; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.blackberry.bdp.krackle.Constants; import com.blackberry.bdp.krackle.KafkaError; import com.blackberry.bdp.krackle.MetricRegistrySingleton; import com.blackberry.bdp.krackle.compression.Compressor; import com.blackberry.bdp.krackle.compression.GzipCompressor; import com.blackberry.bdp.krackle.compression.SnappyCompressor; import com.blackberry.bdp.krackle.meta.Broker; import com.blackberry.bdp.krackle.meta.MetaData; import com.blackberry.bdp.krackle.meta.Topic; import com.codahale.metrics.Gauge; import com.codahale.metrics.Meter; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; /** * An implementation of the Kafka 0.8 producer. * * This class acts as a producer of data to a cluster of Kafka brokers. Each * instance only sends data for a single topic, using a single key. If you need * to write to more topics (or using different keys), then instantiate more * instances. * * This producer is asynchonous only. There is no synchronous mode. * * This class was designed to be very light weight. The standard Java client * creates a lot of objects, and therefore causes a lot of garbage collection * that leads to a major slowdown in performance. This client creates ver few * new objects during steady state running, and so avoids most garbage * collection overhead. */ public class Producer { private static final Logger LOG = LoggerFactory.getLogger(Producer.class); private static final Charset UTF8 = Charset.forName("UTF-8"); private ProducerConfiguration conf; private String clientIdString; private byte[] clientIdBytes; private short clientIdLength; private String keyString; private int partitionModifier; private byte[] keyBytes; private int keyLength; private String topicString; private byte[] topicBytes; private short topicLength; // Various configs private short requiredAcks; private int brokerTimeout; private int retries; private int compressionLevel; private int retryBackoffMs; private long topicMetadataRefreshIntervalMs; private long queueBufferingMaxMs; // Store the uncompressed message set that we will be compressing later. private int numBuffers; private BlockingQueue<MessageSetBuffer> freeBuffers = null; private static final Object sharedBufferLock = new Object(); private static BlockingQueue<MessageSetBuffer> sharedBuffers = null; private BlockingQueue<MessageSetBuffer> buffersToSend; // Store the compressed message + headers. // Generally, this needs to be bigger than the messageSetBufferSize // for uncompressed messages (size + key length + topic length + 34?) // For compressed messages, this shouldn't need to be bigger. private int sendBufferSize; // How to compress! Compressor compressor; // We could be using crc in 2 separate blocks, which could cause corruption // with one instance. private CRC32 crcSend = new CRC32(); //private Sender sender = null; private ArrayList<Thread> senderThreads = new ArrayList<>(); private ArrayList<Sender> senders = new ArrayList<>(); private boolean closed = false; private ScheduledExecutorService scheduledExecutor = Executors .newSingleThreadScheduledExecutor(); private MetricRegistry metrics; private Meter mReceived = null; private Meter mReceivedTotal = null; private Meter mSent = null; private Meter mSentTotal = null; private Meter mDroppedQueueFull = null; private Meter mDroppedQueueFullTotal = null; private Meter mDroppedSendFail = null; private Meter mDroppedSendFailTotal = null; private String freeBufferGaugeName; /** * Create a new producer using a given instance of MetricRegistry instead of * the default singleton. * * @param conf * ProducerConfiguration to use * @param clientId * client id to send to the brokers * @param topic * topic to produce on * @param key * key to use for partitioning * @param metrics * MetricRegistry instance to use for metrics. * @throws Exception */ public Producer(ProducerConfiguration conf, String clientId, String topic, String key, MetricRegistry metrics) throws Exception { LOG.info("Creating new producer for topic {}, key {}", topic, key); this.conf = conf; clientId = clientId + "-" + Long.toHexString(Double.doubleToLongBits(Math.random())); LOG.info("Client ID: {}", clientId); this.topicString = topic; this.topicBytes = topic.getBytes(UTF8); this.topicLength = (short) topicBytes.length; this.clientIdString = clientId; this.clientIdBytes = clientId.getBytes(UTF8); this.clientIdLength = (short) clientId.length(); this.keyString = key; this.keyBytes = key.getBytes(UTF8); this.keyLength = keyBytes.length; this.partitionModifier = 0; if (metrics == null) { this.metrics = MetricRegistrySingleton.getInstance().getMetricsRegistry(); MetricRegistrySingleton.getInstance().enableJmx(); MetricRegistrySingleton.getInstance().enableConsole(); } else { this.metrics = metrics; } initializeMetrics(); configure(); // Start a periodic sender to ensure that things get sent from time to // time. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { send(null, 0, 0); } catch (Exception e) { // That's fine. } } }, queueBufferingMaxMs, queueBufferingMaxMs, TimeUnit.MILLISECONDS); // Create the sender objects and threads for (int i = 0; i < conf.getSenderThreads(); i++) { Sender sender = new Sender(); Thread senderThread = new Thread(sender); senderThread.setDaemon(false); LOG.debug("[{}] Creating Sender Thread-{} ({})", topicString, i, senderThread.toString()); senderThread.setName("Sender-Thread-" + i + "-" + senderThread.getId()); senderThread.start(); senderThreads.add(senderThread); senders.add(sender); } // Ensure that if the sender thread ever dies, it is restarted. scheduledExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { ArrayList<Thread> toRemove = new ArrayList<Thread>(); ArrayList<Thread> toAdd = new ArrayList<Thread>(); for(Thread senderThread : senderThreads) { if (senderThread == null || senderThread.isAlive() == false) { Sender sender = new Sender(); toRemove.add(senderThread); LOG.error("[{}] Sender thread {} clientId {} is dead! Restarting it.", topicString, senderThread.getName(), clientIdString); senderThread = new Thread(sender); senderThread.setDaemon(false); senderThread.setName("Sender-Thread-" + senderThread.getId()); senderThread.start(); toAdd.add(senderThread); } } for(Thread removeThread: toRemove) { senderThreads.remove(removeThread); } for(Thread addThread: toAdd) { senderThreads.add(addThread); } } }, 1, 1, TimeUnit.MINUTES); } private void initializeMetrics() { String name = topicString; mReceived = this.metrics.meter("krackle:producer:topics:" + name + ":messages received"); mReceivedTotal = this.metrics .meter("krackle:producer:total:messages received"); mSent = this.metrics.meter("krackle:producer:topics:" + name + ":messages sent"); mSentTotal = this.metrics.meter("krackle:producer:total:messages sent"); mDroppedQueueFull = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (queue full)"); mDroppedQueueFullTotal = this.metrics .meter("krackle:producer:total:messages dropped (queue full)"); mDroppedSendFail = this.metrics.meter("krackle:producer:topics:" + name + ":messages dropped (send failure)"); mDroppedSendFailTotal = this.metrics .meter("krackle:producer:total:messages dropped (send failure)"); } private void configure() throws Exception { requiredAcks = conf.getRequestRequiredAcks(); retryBackoffMs = conf.getRetryBackoffMs(); brokerTimeout = conf.getRequestTimeoutMs(); retries = conf.getMessageSendMaxRetries(); sendBufferSize = conf.getSendBufferSize(); topicMetadataRefreshIntervalMs = conf.getTopicMetadataRefreshIntervalMs(); queueBufferingMaxMs = conf.getQueueBufferingMaxMs(); String compressionCodec = conf.getCompressionCodec(); compressionLevel = conf.getCompressionLevel(); int messageBufferSize = conf.getMessageBufferSize(); numBuffers = conf.getNumBuffers(); // Check to see if we're using a shared buffer, or dedicated buffers. if (conf.isUseSharedBuffers()) { synchronized (sharedBufferLock) { if (sharedBuffers == null) { sharedBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { sharedBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } MetricRegistrySingleton .getInstance() .getMetricsRegistry() .register("krackle:producer:shared free buffers", new Gauge<Integer>() { @Override public Integer getValue() { return sharedBuffers.size(); } }); } } freeBuffers = sharedBuffers; } else { freeBuffers = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); for (int i = 0; i < numBuffers; i++) { freeBuffers.add(new MessageSetBuffer(this, messageBufferSize)); } freeBufferGaugeName = "krackle:producer:topics:" + topicString + ":free buffers"; if (MetricRegistrySingleton.getInstance().getMetricsRegistry() .getGauges(new MetricFilter() { @Override public boolean matches(String s, Metric m) { return s.equals(freeBufferGaugeName); } }).size() > 0) { LOG.warn("Gauge already exists for '{}'", freeBufferGaugeName); } else { MetricRegistrySingleton.getInstance().getMetricsRegistry() .register(freeBufferGaugeName, new Gauge<Integer>() { @Override public Integer getValue() { return freeBuffers.size(); } }); } } buffersToSend = new ArrayBlockingQueue<MessageSetBuffer>(numBuffers); if (compressionCodec.equals("none")) { compressor = null; } else if (compressionCodec.equals("snappy")) { compressor = new SnappyCompressor(); } else if (compressionCodec.equals("gzip")) { compressor = new GzipCompressor(compressionLevel); } else { throw new Exception("Unknown compression type: " + compressionCodec); } } private int crcPos; private MessageSetBuffer activeMessageSetBuffer = null; private ByteBuffer activeByteBuffer; /** * Add a message to the send queue * * Takes bytes from buffer from start, up to length bytes. * * @param buffer * byte array to read from. * @param offset * location in source to start from. * @param length * length of input data to read. * @throws Exception */ public synchronized void send(byte[] buffer, int offset, int length) throws Exception { if (closed) { LOG.warn("Trying to send data on a closed producer."); return; } if (activeMessageSetBuffer == null) { if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } // null buffer means send what we have if (buffer == null) { if (activeMessageSetBuffer.getBatchSize() > 0) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; } return; } mReceived.mark(); mReceivedTotal.mark(); if (activeMessageSetBuffer.getBuffer().remaining() < length + keyLength + 26) { buffersToSend.put(activeMessageSetBuffer); activeMessageSetBuffer = null; if (conf.getQueueEnqueueTimeoutMs() == -1) { activeMessageSetBuffer = freeBuffers.take(); } else { activeMessageSetBuffer = freeBuffers.poll( conf.getQueueEnqueueTimeoutMs(), TimeUnit.MILLISECONDS); } if (activeMessageSetBuffer == null) { mDroppedQueueFull.mark(); mDroppedQueueFullTotal.mark(); return; } } activeByteBuffer = activeMessageSetBuffer.getBuffer(); // Offset activeByteBuffer.putLong(0L); // Size of uncompressed message activeByteBuffer.putInt(length + keyLength + 14); crcPos = activeByteBuffer.position(); activeByteBuffer.position(crcPos + 4); // magic number activeByteBuffer.put(Constants.MAGIC_BYTE); // no compression activeByteBuffer.put(Constants.NO_COMPRESSION); activeByteBuffer.putInt(keyLength); // Key length activeByteBuffer.put(keyBytes); // Key activeByteBuffer.putInt(length); // Value length activeByteBuffer.put(buffer, offset, length); // Value crcSend.reset(); crcSend.update(activeMessageSetBuffer.getBytes(), crcPos + 4, length + keyLength + 10); activeByteBuffer.putInt(crcPos, (int) crcSend.getValue()); activeMessageSetBuffer.incrementBatchSize(); } int nextLoadingBuffer; boolean incrementLoadingBufferResult; private String getErrorString(short errorCode) { for (KafkaError e : KafkaError.values()) { if (e.getCode() == errorCode) { return e.getMessage(); } } return null; } public synchronized void close() { LOG.info("Closing producer."); closed = true; buffersToSend.add(activeMessageSetBuffer); activeMessageSetBuffer = null; try { for(Thread senderThread : senderThreads) { senderThread.join(); } } catch (InterruptedException e) { LOG.error("Error shutting down sender and loader threads.", e); } if (conf.isUseSharedBuffers() == false) { MetricRegistrySingleton.getInstance().getMetricsRegistry() .remove(freeBufferGaugeName); } } private class Sender implements Runnable { private MessageSetBuffer buffer; private int lastLatency = 0; private int correlationId = 0; private byte[] toSendBytes; private ByteBuffer toSendBuffer; private int messageSetSizePos; private int messageSizePos; private int messageCompressedSize; private CRC32 crcSendMessage = new CRC32(); private Random rand = new Random(); // Buffer for reading responses from the server. private byte[] responseBytes; private ByteBuffer responseBuffer; private int responseSize; private int responseCorrelationId; private short responseErrorCode; private int retry; private Socket socket; private OutputStream out; private InputStream in; private String clientThreadIdString; private byte[] clientThreadIdBytes; private short clientThreadIdLength; private MetaData metadata; private long lastMetadataRefresh; private int partition; private Broker broker; private String brokerAddress = null; public Sender() { toSendBytes = new byte[sendBufferSize]; toSendBuffer = ByteBuffer.wrap(toSendBytes); // We need this to be big enough to read the length of the first response, // then we can expand it to the appropriate size. responseBytes = new byte[4]; responseBuffer = ByteBuffer.wrap(responseBytes); // Try to do this. If it fails, then we can try again when it's time to // send. try { // In case this fails, we don't want the value to be null; lastMetadataRefresh = System.currentTimeMillis(); updateMetaDataAndConnection(true); } catch (Throwable t) { LOG.warn("Initial load of metadata failed.", t); metadata = null; } } private void updateMetaDataAndConnection(boolean force) throws MissingPartitionsException { LOG.info("{} - Updating metadata", Thread.currentThread().getName()); metadata = MetaData.getMetaData(conf.getMetadataBrokerList(), topicString, clientIdString ); LOG.debug("Metadata: {}", metadata); Topic topic = metadata.getTopic(topicString); if (topic.getNumPartitions() == 0) { throw new MissingPartitionsException(String.format("Topic %s has zero partitions", topicString), null); } if (!force) { //We don't rotate if it's a forced meta-data refresh, as we would have a block in the queue waiting to send if(conf.getPartitionsRotate() == 1) { //rotate sequentially partitionModifier = (partitionModifier + 1) % topic.getNumPartitions(); LOG.info("Metadata and connection refresh called without force, partition modifier is now: {}", partitionModifier); } else if (conf.getPartitionsRotate() == 2) { //pick a random number to increase partitions by partitionModifier = rand.nextInt(topic.getNumPartitions()); } } partition = (Math.abs(keyString.hashCode()) + partitionModifier) % topic.getNumPartitions(); LOG.info("Sending to partition {} of {}", partition, topic.getNumPartitions()); broker = metadata.getBroker(topic.getPartition(partition).getLeader()); // Only reset our connection if the broker has changed, or it's forced String newBrokerAddress = broker.getHost() + ":" + broker.getPort(); if (force || brokerAddress == null || brokerAddress.equals(newBrokerAddress) == false) { brokerAddress = newBrokerAddress; LOG.info("Changing brokers to {}", broker); if (socket != null) { try { socket.close(); } catch (IOException e) { LOG.error("Error closing connection to broker.", e); } } try { socket = new Socket(broker.getHost(), broker.getPort()); socket.setSendBufferSize(conf.getSendBufferSize()); socket.setSoTimeout(conf.getRequestTimeoutMs() + 1000); LOG.info("Connected to {}", socket); in = socket.getInputStream(); out = socket.getOutputStream(); } catch (UnknownHostException e) { LOG.error("Error connecting to broker.", e); } catch (IOException e) { LOG.error("Error connecting to broker.", e); } } lastMetadataRefresh = System.currentTimeMillis(); } // Send accumulated messages protected void sendMessage(MessageSetBuffer messageSetBuffer) { try { // New message, new id correlationId++; /* headers */ // Skip 4 bytes for the size toSendBuffer.position(4); // API key for produce toSendBuffer.putShort(Constants.APIKEY_PRODUCE); // Version toSendBuffer.putShort(Constants.API_VERSION); // Correlation Id toSendBuffer.putInt(correlationId); // Client Id toSendBuffer.putShort(clientIdLength); toSendBuffer.put(clientIdBytes); // Required Acks toSendBuffer.putShort(requiredAcks); // Timeout in ms toSendBuffer.putInt(brokerTimeout); // Number of topics toSendBuffer.putInt(1); // Topic name toSendBuffer.putShort(topicLength); toSendBuffer.put(topicBytes); // Number of partitions toSendBuffer.putInt(1); // Partition toSendBuffer.putInt(partition); if (compressor == null) { // If we 're not compressing, then we can just dump the rest of the // message here. // Message set size toSendBuffer.putInt(messageSetBuffer.getBuffer().position()); // Message set toSendBuffer.put(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position()); } else { // If we are compressing, then do that. // Message set size ? We'll have to do this later. messageSetSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 4); // offset can be anything for produce requests. We'll use 0 toSendBuffer.putLong(0L); // Skip 4 bytes for size, and 4 for crc messageSizePos = toSendBuffer.position(); toSendBuffer.position(toSendBuffer.position() + 8); toSendBuffer.put(Constants.MAGIC_BYTE); // magic number toSendBuffer.put(compressor.getAttribute()); // Compression goes // here. // Add the key toSendBuffer.putInt(keyLength); toSendBuffer.put(keyBytes); // Compress the value here, into the toSendBuffer try { messageCompressedSize = compressor.compress(messageSetBuffer.getBytes(), 0, messageSetBuffer.getBuffer().position(), toSendBytes, toSendBuffer.position() + 4); if (messageCompressedSize == -1) { // toSendBytes is too small to hold the compressed data throw new IOException( "Not enough room in the send buffer for the compressed data."); } } catch (IOException e) { LOG.error("Exception while compressing data. (data lost).", e); return; } // Write the size toSendBuffer.putInt(messageCompressedSize); // Update the send buffer position toSendBuffer.position(toSendBuffer.position() + messageCompressedSize); /** Go back and fill in the missing pieces **/ // Message Set Size toSendBuffer.putInt(messageSetSizePos, toSendBuffer.position() - (messageSetSizePos + 4)); // Message Size toSendBuffer.putInt(messageSizePos, toSendBuffer.position() - (messageSizePos + 4)); // Message CRC crcSendMessage.reset(); crcSendMessage.update(toSendBytes, messageSizePos + 8, toSendBuffer.position() - (messageSizePos + 8)); toSendBuffer.putInt(messageSizePos + 4, (int) crcSendMessage.getValue()); } // Fill in the complete message size toSendBuffer.putInt(0, toSendBuffer.position() - 4); // Send it! retry = 0; while (retry <= retries) { try { if (metadata == null || socket == null) { updateMetaDataAndConnection(true); } LOG.debug("[{}] Sender Thread-{} ({}) Sending Block with CorrelationId: {} ClientId: {} Socket: {}", topicString, senderThreads.indexOf(Thread.currentThread()), Thread.currentThread().getId(), correlationId, clientIdString, socket.toString()); // Send request out.write(toSendBytes, 0, toSendBuffer.position()); if (requiredAcks != 0) { // Check response responseBuffer.clear(); in.read(responseBytes, 0, 4); responseSize = responseBuffer.getInt(); if (responseBuffer.capacity() < responseSize) { responseBytes = new byte[responseSize]; responseBuffer = ByteBuffer.wrap(responseBytes); } responseBuffer.clear(); in.read(responseBytes, 0, responseSize); // Response bytes are // - 4 byte correlation id // - 4 bytes for number of topics. This is always 1 in this case. // - 2 bytes for length of topic name. // - topicLength bytes for topic // - 4 bytes for number of partitions. Always 1. // - 4 bytes for partition number (which we already know) // - 2 bytes for error code (That's interesting to us) // - 8 byte offset of the first message (we don't care). // The only things we care about here are the correlation id (must // match) and the error code (so we can throw an exception if it's // not 0) responseCorrelationId = responseBuffer.getInt(); if (responseCorrelationId != correlationId) { throw new Exception("Correlation ID mismatch. Expected " + correlationId + ", got " + responseCorrelationId + " ClientID: " + clientIdString + " Socket: " + socket.toString()); } responseErrorCode = responseBuffer.getShort(18 + topicLength); if (responseErrorCode != KafkaError.NoError.getCode()) { throw new Exception("Got error from broker. Error Code " + responseErrorCode + " (" + getErrorString(responseErrorCode) + ")"); } // Clear the responses, if there is anything else to read while (in.available() > 0) { in.read(responseBytes, 0, responseBytes.length); } } break; } catch (Throwable t) { metadata = null; retry++; if (retry <= retries) { LOG.warn("Request failed. Retrying {} more times for {}.", retries - retry + 1, topicString, t); try { Thread.sleep(retryBackoffMs); } catch (InterruptedException e) { // Do nothing } } else { LOG.error("Request failed. No more retries (data lost) for {}.", topicString, t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } } toSendBuffer.clear(); mSent.mark(messageSetBuffer.getBatchSize()); mSentTotal.mark(messageSetBuffer.getBatchSize()); // Periodic metadata refreshes. if ((topicMetadataRefreshIntervalMs >= 0 && System.currentTimeMillis() - lastMetadataRefresh >= topicMetadataRefreshIntervalMs)) { try { updateMetaDataAndConnection(false); } catch (Throwable t) { LOG.error("Error refreshing metadata.", t); } } } catch (Throwable t) { LOG.error("Unexpected exception: {}", t); mDroppedSendFail.mark(messageSetBuffer.getBatchSize()); mDroppedSendFailTotal.mark(messageSetBuffer.getBatchSize()); } } @Override public void run() { float sendStart = 0; this.clientThreadIdString = clientIdString + "-" + Thread.currentThread().getId(); this.clientThreadIdBytes = clientThreadIdString.getBytes(UTF8); this.clientThreadIdLength = (short) clientThreadIdString.length(); LOG.debug("Starting Run Of Sender Thread: " + Thread.currentThread().getId()); String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread()) + ":blockTransmitTime - ms"; MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName, new Gauge<Integer>() { @Override public Integer getValue() { return lastLatency; } }); while (true) { try { if (closed && buffersToSend.isEmpty()) { break; } try { buffer = buffersToSend.poll(1, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Interrupted polling for a new buffer.", e); continue; } if (buffer == null) { continue; } sendStart = System.currentTimeMillis(); sendMessage(buffer); buffer.clear(); freeBuffers.add(buffer); lastLatency = (int)(System.currentTimeMillis() - sendStart); } catch (Throwable t) { LOG.error("Unexpected error", t); } } LOG.debug("Finishing Run Of Sender Thread: " + Thread.currentThread().getId()); } } }
Added more verbose log line
src/main/java/com/blackberry/bdp/krackle/producer/Producer.java
Added more verbose log line
<ide><path>rc/main/java/com/blackberry/bdp/krackle/producer/Producer.java <ide> this.clientThreadIdString = clientIdString + "-" + Thread.currentThread().getId(); <ide> this.clientThreadIdBytes = clientThreadIdString.getBytes(UTF8); <ide> this.clientThreadIdLength = (short) clientThreadIdString.length(); <del> LOG.debug("Starting Run Of Sender Thread: " + Thread.currentThread().getId()); <add> LOG.debug("Starting Run Of Sender Thread: " + Thread.currentThread().getName()+ "-"+ Thread.currentThread().getId()); <ide> <ide> String metricName = "krackle:producer:" + topicString + ":thread_" + senderThreads.indexOf(Thread.currentThread()) + ":blockTransmitTime - ms"; <ide> MetricRegistrySingleton.getInstance().getMetricsRegistry().register(metricName,
Java
apache-2.0
f84b8f9c4ff26a8fbb2bcd5ae2edc1cf44d890fe
0
arcao/Trackables
package com.arcao.trackables.ui.adapter; import android.support.v7.widget.RecyclerView; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StrikethroughSpan; import android.view.*; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import com.arcao.geocaching.api.data.Trackable; import com.arcao.trackables.R; import com.arcao.trackables.ui.MainActivityComponent; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.typeface.IIcon; import com.squareup.picasso.Picasso; import org.apache.commons.lang3.StringUtils; import timber.log.Timber; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; public class TrackableListAdapter extends RecyclerView.Adapter<TrackableListAdapter.ViewHolder> { private final List<Trackable> trackables = new ArrayList<>(); private MainActivityComponent component; public TrackableListAdapter(MainActivityComponent component) { this.component = component; component.inject(this); } public void setTrackables(List<Trackable> trackables) { this.trackables.clear(); this.trackables.addAll(trackables); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_trackable_list_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bind(trackables.get(position)); } @Override public int getItemCount() { return trackables.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @InjectView(R.id.image) protected ImageView imageView; @InjectView(R.id.title) protected TextView titleTextView; @InjectView(R.id.trackableCodeText) protected TextView trackableCodeTextView; @InjectView(R.id.positionText) protected TextView positionTextView; @Inject protected Picasso picasso; public ViewHolder(View view) { super(view); ButterKnife.inject(this, view); component.inject(this); } public void bind(Trackable trackable) { SpannableString title = new SpannableString(trackable.getName()); if (trackable.isArchived()) { title.setSpan(new StrikethroughSpan(), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } titleTextView.setText(title); applyIcon(trackableCodeTextView, GoogleMaterial.Icon.gmd_label); trackableCodeTextView.setText(trackable.getTrackingNumber()); imageView.setScaleType(ImageView.ScaleType.CENTER); if (trackable.getImages().size() > 0) { Timber.d("Loading image: %s", trackable.getImages().get(0).getUrl()); picasso.load(trackable.getImages().get(0).getUrl()) .resize(imageView.getLayoutParams().width, imageView.getLayoutParams().height) .centerCrop().into(imageView); } else { Timber.d("Loading image: %s", trackable.getTrackableTypeImage()); picasso.load(trackable.getTrackableTypeImage()).resize(dpToPx(32), dpToPx(32)).into(imageView); } if (!StringUtils.isEmpty(trackable.getCurrentCacheCode())) { applyIcon(positionTextView, GoogleMaterial.Icon.gmd_place); positionTextView.setText(trackable.getCurrentCacheCode()); } else if (trackable.getCurrentOwner() != null) { applyIcon(positionTextView, GoogleMaterial.Icon.gmd_person); positionTextView.setText(trackable.getCurrentOwner().getUserName()); } } private void applyIcon(TextView target, IIcon icon) { target.setCompoundDrawables( new IconicsDrawable(target.getContext(), icon).colorRes(R.color.divider).sizeDp(10).iconOffsetYDp(1), null, null, null); } private int dpToPx(int dp) { float density = itemView.getResources().getDisplayMetrics().density; return Math.round((float)dp * density); } } }
app/src/main/java/com/arcao/trackables/ui/adapter/TrackableListAdapter.java
package com.arcao.trackables.ui.adapter; import android.support.v7.widget.RecyclerView; import android.view.*; import android.widget.ImageView; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.InjectView; import com.arcao.geocaching.api.data.Trackable; import com.arcao.trackables.R; import com.arcao.trackables.ui.MainActivityComponent; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.typeface.IIcon; import com.squareup.picasso.Picasso; import org.apache.commons.lang3.StringUtils; import timber.log.Timber; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; public class TrackableListAdapter extends RecyclerView.Adapter<TrackableListAdapter.ViewHolder> { private final List<Trackable> trackables = new ArrayList<>(); private MainActivityComponent component; public TrackableListAdapter(MainActivityComponent component) { this.component = component; component.inject(this); } public void setTrackables(List<Trackable> trackables) { this.trackables.clear(); this.trackables.addAll(trackables); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_trackable_list_item, parent, false)); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bind(trackables.get(position)); } @Override public int getItemCount() { return trackables.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @InjectView(R.id.image) protected ImageView imageView; @InjectView(R.id.title) protected TextView titleTextView; @InjectView(R.id.trackableCodeText) protected TextView trackableCodeTextView; @InjectView(R.id.positionText) protected TextView positionTextView; @Inject protected Picasso picasso; public ViewHolder(View view) { super(view); ButterKnife.inject(this, view); component.inject(this); } public void bind(Trackable trackable) { titleTextView.setText(trackable.getName()); applyIcon(trackableCodeTextView, GoogleMaterial.Icon.gmd_label); trackableCodeTextView.setText(trackable.getTrackingNumber()); imageView.setScaleType(ImageView.ScaleType.CENTER); if (trackable.getImages().size() > 0) { Timber.d("Loading image: %s", trackable.getImages().get(0).getUrl()); picasso.load(trackable.getImages().get(0).getUrl()) .resize(imageView.getLayoutParams().width, imageView.getLayoutParams().height) .centerCrop().into(imageView); } else { Timber.d("Loading image: %s", trackable.getTrackableTypeImage()); picasso.load(trackable.getTrackableTypeImage()).resize(dpToPx(32), dpToPx(32)).into(imageView); } if (!StringUtils.isEmpty(trackable.getCurrentCacheCode())) { applyIcon(positionTextView, GoogleMaterial.Icon.gmd_place); positionTextView.setText(trackable.getCurrentCacheCode()); } else if (trackable.getCurrentOwner() != null) { applyIcon(positionTextView, GoogleMaterial.Icon.gmd_person); positionTextView.setText(trackable.getCurrentOwner().getUserName()); } } private void applyIcon(TextView target, IIcon icon) { target.setCompoundDrawables( new IconicsDrawable(target.getContext(), icon).colorRes(R.color.divider).sizeDp(10).iconOffsetYDp(1), null, null, null); } private int dpToPx(int dp) { float density = itemView.getResources().getDisplayMetrics().density; return Math.round((float)dp * density); } } }
Strike-through archived Trackables in list
app/src/main/java/com/arcao/trackables/ui/adapter/TrackableListAdapter.java
Strike-through archived Trackables in list
<ide><path>pp/src/main/java/com/arcao/trackables/ui/adapter/TrackableListAdapter.java <ide> package com.arcao.trackables.ui.adapter; <ide> <ide> import android.support.v7.widget.RecyclerView; <add>import android.text.Spannable; <add>import android.text.SpannableString; <add>import android.text.style.StrikethroughSpan; <ide> import android.view.*; <ide> import android.widget.ImageView; <ide> import android.widget.TextView; <ide> } <ide> <ide> public void bind(Trackable trackable) { <del> titleTextView.setText(trackable.getName()); <add> SpannableString title = new SpannableString(trackable.getName()); <ide> <add> if (trackable.isArchived()) { <add> title.setSpan(new StrikethroughSpan(), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); <add> } <ide> <add> titleTextView.setText(title); <ide> <ide> applyIcon(trackableCodeTextView, GoogleMaterial.Icon.gmd_label); <ide> trackableCodeTextView.setText(trackable.getTrackingNumber());
Java
mit
5f04c9de4f8d944e830dd927cf460daa4936fc45
0
PG85/OpenTerrainGenerator
package com.pg85.otg.gen.biome.layers; import static com.pg85.otg.gen.biome.layers.BiomeLayers.GROUP_SHIFT; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.pg85.otg.gen.biome.layers.type.ParentedLayer; import com.pg85.otg.gen.biome.layers.util.LayerRandomnessSource; import com.pg85.otg.gen.biome.layers.util.LayerSampleContext; import com.pg85.otg.gen.biome.layers.util.LayerSampler; /** * Places a biome group at a certain depth. */ class BiomeGroupLayer implements ParentedLayer { // The sorted map of rarities to biome groups private final TreeMap<Integer, NewBiomeGroup> rarityMap = new TreeMap<>(); // The rarity sum of all the groups. This is used to choose the biome group. private final int maxRarity; BiomeGroupLayer(List<NewBiomeGroup> groups) { int maxRarity = 0; // Iterate through groups and keep a tally of the rarity of each group. // The order doesn't matter all that much, the margin between the values dictates the rarity. for (NewBiomeGroup group : groups) { maxRarity += group.rarity; this.rarityMap.put(maxRarity, group); } this.maxRarity = maxRarity; } @Override public int sample(LayerSampleContext<?> context, LayerSampler parent, int x, int z) { int sample = parent.sample(x, z); // Check if it's land and then check if there is no group already here if (BiomeLayers.isLand(sample) && BiomeLayers.getGroupId(sample) == 0) { int biomeGroup = getGroup(context); // Encode the biome group id into the sample for later use return sample | (biomeGroup << GROUP_SHIFT); } return sample; } private int getGroup(LayerRandomnessSource random) { // Get a random rarity number from our max rarity // Allow for a "no value" rarity roll, as we did for 1.12. int chosenRarity = random.nextInt(this.rarityMap.size() * 100); // Iterate through the rarity map and see if the chosen rarity is less than the rarity for each group, if it is then return. for (Map.Entry<Integer, NewBiomeGroup> entry : rarityMap.entrySet()) { if (chosenRarity < entry.getKey()) { return entry.getValue().id; } } // Don't place a biome group at this depth return 0; } }
common/common-generator/src/main/java/com/pg85/otg/gen/biome/layers/BiomeGroupLayer.java
package com.pg85.otg.gen.biome.layers; import static com.pg85.otg.gen.biome.layers.BiomeLayers.GROUP_SHIFT; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.pg85.otg.gen.biome.layers.type.ParentedLayer; import com.pg85.otg.gen.biome.layers.util.LayerRandomnessSource; import com.pg85.otg.gen.biome.layers.util.LayerSampleContext; import com.pg85.otg.gen.biome.layers.util.LayerSampler; /** * Places a biome group at a certain depth. */ class BiomeGroupLayer implements ParentedLayer { // The sorted map of rarities to biome groups private final TreeMap<Integer, NewBiomeGroup> rarityMap = new TreeMap<>(); // The rarity sum of all the groups. This is used to choose the biome group. private final int maxRarity; BiomeGroupLayer(List<NewBiomeGroup> groups) { int maxRarity = 0; // Iterate through groups and keep a tally of the rarity of each group. // The order doesn't matter all that much, the margin between the values dictates the rarity. for (NewBiomeGroup group : groups) { maxRarity += group.rarity; this.rarityMap.put(maxRarity, group); } this.maxRarity = maxRarity; } @Override public int sample(LayerSampleContext<?> context, LayerSampler parent, int x, int z) { int sample = parent.sample(x, z); // Check if it's land and then check if there is no group already here if (BiomeLayers.isLand(sample) && BiomeLayers.getGroupId(sample) == 0) { int biomeGroup = getGroup(context); // Encode the biome group id into the sample for later use return sample | biomeGroup << GROUP_SHIFT; } return sample; } private int getGroup(LayerRandomnessSource random) { // Get a random rarity number from our max rarity int chosenRarity = random.nextInt(maxRarity); // Iterate through the rarity map and see if the chosen rarity is less than the rarity for each group, if it is then return. for (Map.Entry<Integer, NewBiomeGroup> entry : rarityMap.entrySet()) { if (chosenRarity < entry.getKey()) { return entry.getValue().id; } } // Fallback return 0; } }
1.16.3 - 0.0.1: biomegroups fixes (hopefully, still broke tho)
common/common-generator/src/main/java/com/pg85/otg/gen/biome/layers/BiomeGroupLayer.java
1.16.3 - 0.0.1: biomegroups fixes (hopefully, still broke tho)
<ide><path>ommon/common-generator/src/main/java/com/pg85/otg/gen/biome/layers/BiomeGroupLayer.java <ide> maxRarity += group.rarity; <ide> this.rarityMap.put(maxRarity, group); <ide> } <del> <add> <ide> this.maxRarity = maxRarity; <ide> } <ide> <ide> public int sample(LayerSampleContext<?> context, LayerSampler parent, int x, int z) <ide> { <ide> int sample = parent.sample(x, z); <del> <add> <ide> // Check if it's land and then check if there is no group already here <ide> if (BiomeLayers.isLand(sample) && BiomeLayers.getGroupId(sample) == 0) <ide> { <ide> int biomeGroup = getGroup(context); <del> <add> <ide> // Encode the biome group id into the sample for later use <del> return sample | biomeGroup << GROUP_SHIFT; <add> return sample | (biomeGroup << GROUP_SHIFT); <ide> } <ide> <ide> return sample; <ide> private int getGroup(LayerRandomnessSource random) <ide> { <ide> // Get a random rarity number from our max rarity <del> int chosenRarity = random.nextInt(maxRarity); <add> // Allow for a "no value" rarity roll, as we did for 1.12. <add> int chosenRarity = random.nextInt(this.rarityMap.size() * 100); <ide> <ide> // Iterate through the rarity map and see if the chosen rarity is less than the rarity for each group, if it is then return. <ide> for (Map.Entry<Integer, NewBiomeGroup> entry : rarityMap.entrySet()) <ide> } <ide> } <ide> <del> // Fallback <add> // Don't place a biome group at this depth <ide> return 0; <ide> } <ide> }
JavaScript
mit
858a0f13d82d52af9c83c40ee0150e16aa9cb4cf
0
jackchi/everyman
if (Meteor.isServer) { self= this; clinics = new Meteor.Collection("clinics"); clinics._ensureIndex({ loc : "2d" }); users = new Meteor.Collection("user"); Meteor.startup(function () { if (Org.find().count() === 0) { var names = ["Jack Chi", "Zak Zibrat", "Marie Curie", "Carl Friedrich Gauss", "Nikola Tesla", "Claude Shannon", "Ronaldo Barbachano"]; for (var i = 0; i < names.length; i++) Org.insert({name: names[i], score: Math.floor(Random.fraction()*10)*5}); } }); Meteor.methods({ findMarker : function(x,y){ console.log(x); console.log(y); var theCenter = [[x,y],.1]; // returns everything var r = clinics.find({ loc : { "$within" : { "$center" : theCenter }}}).fetch(); console.log(r.length); return r; } }); }
server/server.js
if (Meteor.isServer) { self= this; clinics = new Meteor.Collection("clinics"); clinics._ensureIndex({ loc : "2d" }); users = new Meteor.Collection("user"); Meteor.startup(function () { if (Org.find().count() === 0) { var names = ["Jack Chi", "Zak Zibrat", "Marie Curie", "Carl Friedrich Gauss", "Nikola Tesla", "Claude Shannon", "Ronaldo Barbachano"]; for (var i = 0; i < names.length; i++) Org.insert({name: names[i], score: Math.floor(Random.fraction()*10)*5}); } }); Meteor.methods({ findMarker : function(box){ var theCenter = [box,10]; // just NOT working... ??? return clinics.find({ loc : { "$geoWithin" : { "$center" : theCenter }}}); } }); }
cleanup.. just need to figure out the geomongo query that doesnt return an error...
server/server.js
cleanup.. just need to figure out the geomongo query that doesnt return an error...
<ide><path>erver/server.js <ide> }); <ide> <ide> Meteor.methods({ <del> findMarker : function(box){ <del> var theCenter = [box,10]; <del> // just NOT working... ??? <del> return clinics.find({ loc : { "$geoWithin" : { "$center" : theCenter }}}); <add> findMarker : function(x,y){ <add> console.log(x); <add> console.log(y); <add> var theCenter = [[x,y],.1]; <add> // returns everything <add> var r = clinics.find({ loc : { "$within" : { "$center" : theCenter }}}).fetch(); <add> console.log(r.length); <add> return r; <ide> } <ide> }); <ide> }
Java
mit
e640c139c201b13f220bdb7757d58b0a99ed449c
0
dmullins78/easybatch-framework,EasyBatch/easybatch-framework,EasyBatch/easybatch-framework,dmullins78/easybatch-framework
/* * The MIT License * * Copyright (c) 2015, Mahmoud Ben Hassine ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.easybatch.jdbc; import org.easybatch.core.api.event.step.RecordProcessorEventListener; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * Listener that commits a transaction after writing a predefined number of records (commit-interval). * * @author Mahmoud Ben Hassine ([email protected]) */ public class JdbcTransactionStepListener implements RecordProcessorEventListener { private static final Logger LOGGER = Logger.getLogger(JdbcTransactionStepListener.class.getSimpleName()); private static final int DEFAULT_COMMIT_INTERVAL = 1; private Connection connection; private int commitInterval; private int recordNumber; /** * Create a JDBC transaction listener. * * @param connection the JDBC connection (should be in auto-commit = false) */ public JdbcTransactionStepListener(final Connection connection) { this(connection, DEFAULT_COMMIT_INTERVAL); } /** * Create a JDBC transaction listener. * * @param connection the JDBC connection (should be in auto-commit = false) * @param commitInterval the commit interval */ public JdbcTransactionStepListener(final Connection connection, final int commitInterval) { this.commitInterval = commitInterval; this.connection = connection; this.recordNumber = 0; } @Override public Object beforeRecordProcessing(final Object record) { return record; } @Override public void afterRecordProcessing(final Object record, final Object processingResult) { recordNumber++; try { if (recordNumber % commitInterval == 0) { connection.commit(); LOGGER.info("Committing transaction after " + recordNumber + " record(s)"); recordNumber = 0; } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Unable to commit transaction", e); } } @Override public void onRecordProcessingException(final Object record, final Throwable throwable) { try { connection.rollback(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Unable to rollback transaction", e); } } }
easybatch-jdbc/src/main/java/org/easybatch/jdbc/JdbcTransactionStepListener.java
/* * The MIT License * * Copyright (c) 2015, Mahmoud Ben Hassine ([email protected]) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.easybatch.jdbc; import org.easybatch.core.api.event.step.RecordProcessorEventListener; import java.sql.Connection; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * Listener that commits a transaction after writing a predefined number of records (commit-interval). * * @author Mahmoud Ben Hassine ([email protected]) */ public class JdbcTransactionStepListener implements RecordProcessorEventListener { private static final Logger LOGGER = Logger.getLogger(JdbcTransactionStepListener.class.getSimpleName()); private Connection connection; private int commitInterval; private int recordNumber; /** * Create a JDBC transaction listener. * * @param connection the JDBC connection (should be in auto-commit = false) * @param commitInterval the commit interval */ public JdbcTransactionStepListener(final Connection connection, final int commitInterval) { this.commitInterval = commitInterval; this.connection = connection; this.recordNumber = 0; } @Override public Object beforeRecordProcessing(final Object record) { return record; } @Override public void afterRecordProcessing(final Object record, final Object processingResult) { recordNumber++; try { if (recordNumber % commitInterval == 0) { connection.commit(); LOGGER.info("Committing transaction after " + recordNumber + " record(s)"); recordNumber = 0; } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Unable to commit transaction", e); } } @Override public void onRecordProcessingException(final Object record, final Throwable throwable) { try { connection.rollback(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "Unable to rollback transaction", e); } } }
add constructor with default commitInterval value to 1
easybatch-jdbc/src/main/java/org/easybatch/jdbc/JdbcTransactionStepListener.java
add constructor with default commitInterval value to 1
<ide><path>asybatch-jdbc/src/main/java/org/easybatch/jdbc/JdbcTransactionStepListener.java <ide> <ide> private static final Logger LOGGER = Logger.getLogger(JdbcTransactionStepListener.class.getSimpleName()); <ide> <add> private static final int DEFAULT_COMMIT_INTERVAL = 1; <add> <ide> private Connection connection; <ide> <ide> private int commitInterval; <ide> * Create a JDBC transaction listener. <ide> * <ide> * @param connection the JDBC connection (should be in auto-commit = false) <add> */ <add> public JdbcTransactionStepListener(final Connection connection) { <add> this(connection, DEFAULT_COMMIT_INTERVAL); <add> } <add> <add> /** <add> * Create a JDBC transaction listener. <add> * <add> * @param connection the JDBC connection (should be in auto-commit = false) <ide> * @param commitInterval the commit interval <ide> */ <ide> public JdbcTransactionStepListener(final Connection connection, final int commitInterval) {
Java
apache-2.0
ad3a471ab1d0f2aa94dbca3e0e7c71f8dc71af37
0
Sellegit/j2objc,gank0326/j2objc,csripada/j2objc,gank0326/j2objc,hambroperks/j2objc,ZouQingcang/MyProject,hambroperks/j2objc,ZouQingcang/MyProject,larrytin/j2objc,ZouQingcang/MyProject,larrytin/j2objc,jiachenning/j2objc,hambroperks/j2objc,larrytin/j2objc,ZouQingcang/MyProject,hambroperks/j2objc,gank0326/j2objc,Sellegit/j2objc,gank0326/j2objc,gank0326/j2objc,jiachenning/j2objc,jiachenning/j2objc,hambroperks/j2objc,ZouQingcang/MyProject,hambroperks/j2objc,csripada/j2objc,larrytin/j2objc,larrytin/j2objc,Sellegit/j2objc,hambroperks/j2objc,Sellegit/j2objc,Sellegit/j2objc,csripada/j2objc,jiachenning/j2objc,jiachenning/j2objc
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.google.common.io.CharStreams; import com.google.common.io.Files; import com.google.devtools.j2objc.gen.ObjectiveCHeaderGenerator; import com.google.devtools.j2objc.gen.ObjectiveCImplementationGenerator; import com.google.devtools.j2objc.gen.ObjectiveCSegmentedHeaderGenerator; import com.google.devtools.j2objc.translate.AnonymousClassConverter; import com.google.devtools.j2objc.translate.ArrayRewriter; import com.google.devtools.j2objc.translate.Autoboxer; import com.google.devtools.j2objc.translate.DeadCodeEliminator; import com.google.devtools.j2objc.translate.DestructorGenerator; import com.google.devtools.j2objc.translate.GwtConverter; import com.google.devtools.j2objc.translate.InitializationNormalizer; import com.google.devtools.j2objc.translate.InnerClassExtractor; import com.google.devtools.j2objc.translate.JavaToIOSMethodTranslator; import com.google.devtools.j2objc.translate.JavaToIOSTypeConverter; import com.google.devtools.j2objc.translate.OuterReferenceFixer; import com.google.devtools.j2objc.translate.OuterReferenceResolver; import com.google.devtools.j2objc.translate.Rewriter; import com.google.devtools.j2objc.translate.TypeSorter; import com.google.devtools.j2objc.types.Types; import com.google.devtools.j2objc.util.ASTNodeException; import com.google.devtools.j2objc.util.DeadCodeMap; import com.google.devtools.j2objc.util.NameTable; import com.google.devtools.j2objc.util.ProGuardUsageParser; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; /** * Translation tool for generating Objective C source files from Java sources. * This tool is not intended to be a general purpose converter, but instead is * focused on what is needed for business logic libraries written in Java to * run natively on iOS. In particular, no attempt is made to translate Java * UI framework code to any iOS frameworks. * * @author Tom Ball */ public class J2ObjC { private static String currentFileName; private static CompilationUnit currentUnit; private static int nFiles = 0; private static int nErrors = 0; private static int nWarnings = 0; public enum Language { OBJECTIVE_C(".m"), OBJECTIVE_CPP(".mm"); private final String suffix; private Language(String suffix) { this.suffix = suffix; } public String getSuffix() { return suffix; } } static { // Always enable assertions in translator. ClassLoader loader = J2ObjC.class.getClassLoader(); if (loader != null) { loader.setPackageAssertionStatus(J2ObjC.class.getPackage().getName(), true); } } private static final Logger logger = Logger.getLogger(J2ObjC.class.getName()); /** * Parse a specified Java source file and generate Objective C header(s) * and implementation file(s) from it. * * @param filename the source file to translate */ void translate(String filename) throws IOException { long startTime = System.currentTimeMillis(); int beginningErrorLevel = getCurrentErrorLevel(); logger.finest("reading " + filename); // Read file currentFileName = filename; String source = getSource(filename); if (source == null) { error("no such file: " + filename); return; } long readTime = System.currentTimeMillis(); // Parse and resolve source currentUnit = parse(filename, source); long compileTime = System.currentTimeMillis(); if (getCurrentErrorLevel() > beginningErrorLevel) { return; // Continue to next file. } logger.finest("translating " + filename); long translateTime = 0L; initializeTranslation(currentUnit); try { String newSource = translate(currentUnit, source); translateTime = System.currentTimeMillis(); if (currentUnit.types().isEmpty()) { logger.finest("skipping dead file " + filename); } else { if (Options.printConvertedSources()) { saveConvertedSource(filename, newSource); } logger.finest( "writing output file(s) to " + Options.getOutputDirectory().getAbsolutePath()); // write header if (Options.generateSegmentedHeaders()) { ObjectiveCSegmentedHeaderGenerator.generate(filename, source, currentUnit); } else { ObjectiveCHeaderGenerator.generate(filename, source, currentUnit); } // write implementation file ObjectiveCImplementationGenerator.generate( filename, Options.getLanguage(), currentUnit, source); } } catch (ASTNodeException e) { error(e); } finally { cleanup(); } long endTime = System.currentTimeMillis(); printTimingInfo(readTime - startTime, compileTime - readTime, translateTime - compileTime, endTime - translateTime, endTime - startTime); } private static CompilationUnit parse(String filename, String source) { logger.finest("parsing " + filename); ASTParser parser = ASTParser.newParser(AST.JLS4); Map<String, String> compilerOptions = Options.getCompilerOptions(); parser.setCompilerOptions(compilerOptions); parser.setSource(source.toCharArray()); parser.setResolveBindings(true); setPaths(parser); parser.setUnitName(filename); CompilationUnit unit = (CompilationUnit) parser.createAST(null); for (IProblem problem : getCompilationErrors(unit)) { if (problem.isError()) { error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage())); } } return unit; } private static List<IProblem> getCompilationErrors(CompilationUnit unit) { List<IProblem> errors = Lists.newArrayList(); for (IProblem problem : unit.getProblems()) { if (problem.isError()) { if (((problem.getID() & IProblem.ImportRelated) > 0) && Options.ignoreMissingImports()) { continue; } else { errors.add(problem); } } } return errors; } private void cleanup() { NameTable.cleanup(); Types.cleanup(); OuterReferenceResolver.cleanup(); } /** * Removes dead types and methods, declared in a dead code map. * * @param unit the compilation unit created by ASTParser * @param source the Java source used by ASTParser * @return the rewritten source * @throws AssertionError if the dead code eliminator makes invalid edits */ public static String removeDeadCode(CompilationUnit unit, String source) { if (Options.getDeadCodeMap() == null) { return source; } logger.finest("removing dead code"); new DeadCodeEliminator(Options.getDeadCodeMap()).run(unit); Document doc = new Document(source); TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions()); try { edit.apply(doc); } catch (MalformedTreeException e) { throw new AssertionError(e); } catch (BadLocationException e) { throw new AssertionError(e); } return doc.get(); } private String[] removeDeadCode(String[] files) throws IOException { loadDeadCodeMap(); if (Options.getDeadCodeMap() != null) { for (int i = 0; i < files.length; i++) { String filename = files[i]; logger.finest("reading " + filename); if (filename.endsWith(".java")) { // Read file String source = getSource(filename); if (source == null) { error("no such file: " + filename); return files; } String newPath = removeDeadCode(filename, source); if (!filename.equals(newPath)) { files[i] = newPath; } } else if (filename.endsWith(".jar")) { File f = new File(filename); if (f.exists() && f.isFile()) { ZipFile zfile = new ZipFile(f); try { Enumeration<? extends ZipEntry> enumerator = zfile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); String path = entry.getName(); if (path.endsWith(".java")) { removeDeadCode(path, getSource(path)); } } } finally { zfile.close(); // Also closes input stream. } } } } } Options.insertSourcePath(0, Options.getTemporaryDirectory()); return files; } private String removeDeadCode(String path, String source) throws IOException { long startTime = System.currentTimeMillis(); int beginningErrorLevel = getCurrentErrorLevel(); // Parse and resolve source CompilationUnit unit = parse(path, source); if (getCurrentErrorLevel() > beginningErrorLevel) { return path; } initializeTranslation(unit); String newSource = removeDeadCode(unit, source); if (!newSource.equals(source)) { // Save the new source to the tmpdir and update the files list. String pkg = unit.getPackage().getName().getFullyQualifiedName(); File packageDir = new File(Options.getTemporaryDirectory(), pkg.replace('.', File.separatorChar)); packageDir.mkdirs(); int index = path.lastIndexOf(File.separatorChar); String outputName = index >= 0 ? path.substring(index + 1) : path; File outFile = new File(packageDir, outputName); Files.write(newSource, outFile, Charsets.UTF_8); path = outFile.getAbsolutePath(); } long elapsedTime = System.currentTimeMillis() - startTime; if (logger.getLevel().intValue() <= Level.FINE.intValue()) { System.out.println( String.format("dead-code elimination time: %.3f", inSeconds(elapsedTime))); } return path; } /** * Translates a parsed source file, modifying the compilation unit by * substituting core Java type and method references with iOS equivalents. * For example, <code>java.lang.Object</code> maps to <code>NSObject</code>, * and <code>java.lang.String</code> to <code>NSString</code>. The source is * also modified to add support for iOS memory management, extract inner * classes, etc. * <p> * Note: the returned source file doesn't need to be re-parsed, since the * compilation unit already reflects the changes (it's useful, though, * for dumping intermediate stages). * </p> * * @param unit the compilation unit created by ASTParser * @param source the Java source used by ASTParser * @return the rewritten source * @throws AssertionError if the translator makes invalid edits */ public static String translate(CompilationUnit unit, String source) { // Update code that has GWT references. new GwtConverter().run(unit); // Modify AST to be more compatible with Objective C new Rewriter().run(unit); // Add auto-boxing conversions. new Autoboxer(unit.getAST()).run(unit); // Extract inner and anonymous classes new AnonymousClassConverter(unit).run(unit); new InnerClassExtractor(unit).run(unit); // Normalize init statements new InitializationNormalizer().run(unit); // Fix references to outer scope and captured variables. new OuterReferenceFixer().run(unit); // Translate core Java type use to similar iOS types new JavaToIOSTypeConverter().run(unit); Map<String, String> methodMappings = Options.getMethodMappings(); if (methodMappings.isEmpty()) { // Method maps are loaded here so tests can call translate() directly. loadMappingFiles(); } new JavaToIOSMethodTranslator(unit.getAST(), methodMappings).run(unit); new ArrayRewriter().run(unit); // Reorders the types so that superclasses are declared before classes that // extend them. TypeSorter.sortTypes(unit); // Add dealloc/finalize method(s), if necessary. This is done // after inner class extraction, so that each class releases // only its own instance variables. new DestructorGenerator().run(unit); for (Plugin plugin : Options.getPlugins()) { plugin.processUnit(unit); } // Verify all modified nodes have type bindings Types.verifyNode(unit); Document doc = new Document(source); TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions()); try { edit.apply(doc); } catch (MalformedTreeException e) { throw new AssertionError(e); } catch (BadLocationException e) { throw new AssertionError(e); } return doc.get(); } public static void initializeTranslation(CompilationUnit unit) { unit.recordModifications(); NameTable.initialize(unit); Types.initialize(unit); OuterReferenceResolver.resolve(unit); } private void saveConvertedSource(String filename, String content) { try { File outputFile = new File(Options.getOutputDirectory(), filename); outputFile.getParentFile().mkdirs(); Files.write(content, outputFile, Charset.defaultCharset()); } catch (IOException e) { error(e.getMessage()); } } private static void setPaths(ASTParser parser) { // Add existing boot classpath after declared path, so that core files // referenced, but not being translated, are included. This only matters // when compiling the JRE emulation library sources. List<String> fullClasspath = Lists.newArrayList(); String[] classpathEntries = Options.getClassPathEntries(); for (int i = 0; i < classpathEntries.length; i++) { fullClasspath.add(classpathEntries[i]); } String bootclasspath = Options.getBootClasspath(); for (String path : bootclasspath.split(":")) { // JDT requires that all path elements exist and can hold class files. File f = new File(path); if (f.exists() && (f.isDirectory() || path.endsWith(".jar"))) { fullClasspath.add(path); } } parser.setEnvironment(fullClasspath.toArray(new String[0]), Options.getSourcePathEntries(), Options.getFileEncodings(), true); // Workaround for ASTParser.setEnvironment() bug, which ignores its // last parameter. This has been fixed in the Eclipse post-3.7 Java7 // branch. try { Field field = parser.getClass().getDeclaredField("bits"); field.setAccessible(true); int bits = field.getInt(parser); // Turn off CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH bits &= ~0x20; field.setInt(parser, bits); } catch (Exception e) { // should never happen, since only the one known class is manipulated e.printStackTrace(); System.exit(1); } } private String getSource(String path) throws IOException { File file = findSourceFile(path); if (file == null) { return findArchivedSource(path); } else { return Files.toString(file, Charset.defaultCharset()); } } private File findSourceFile(String filename) { File f = getFileOrNull(filename); if (f != null) { return f; } for (String pathEntry : Options.getSourcePathEntries()) { f = getFileOrNull(pathEntry + File.separatorChar + filename); if (f != null) { return f; } } return null; } private String findArchivedSource(String path) throws IOException { for (String pathEntry : Options.getSourcePathEntries()) { File f = new File(pathEntry); if (f.exists() && f.isFile()) { ZipFile zfile; try { zfile = new ZipFile(f); } catch (ZipException e) { // Not a zip or jar file, so skip it. continue; } ZipEntry entry = zfile.getEntry(path); if (entry == null) { continue; } try { Reader in = new InputStreamReader(zfile.getInputStream(entry)); return CharStreams.toString(in); } finally { zfile.close(); // Also closes input stream. } } } return null; } private File getFileOrNull(String fileName) { File f = new File(fileName); return f.exists() ? f : null; } private static void translateSourceJar(J2ObjC compiler, String jarPath) throws IOException { File f = new File(jarPath); if (f.exists() && f.isFile()) { ZipFile zfile = new ZipFile(f); try { Enumeration<? extends ZipEntry> enumerator = zfile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); String path = entry.getName(); if (path.endsWith(".java")) { printInfo("translating " + path); compiler.translate(path); nFiles++; } } } catch (ZipException e) { // Not a zip or jar file, so skip it. return; } finally { zfile.close(); // Also closes input stream. } } } /** * Translate files listed in a manifest file. */ private static void translateAtFile(J2ObjC compiler, String atFile) throws IOException { if (atFile.isEmpty()) { error("no @ file specified"); exit(); } File f = new File(atFile); if (!f.exists()) { error("no such file: " + atFile); exit(); } String fileList = compiler.getSource(atFile); String[] files = fileList.split("\\s+"); // Split on any whitespace. for (String file : files) { printInfo("translating " + file); compiler.translate(file); nFiles++; } } /** * Report an error during translation. */ public static void error(String message) { System.err.println("error: " + message); error(); } /** * Increment the error counter, but don't display an error diagnostic. * This should only be directly called via tests that are testing * error conditions. */ public static void error() { nErrors++; } /** * Report an ASTVisitor error. */ public static void error(ASTNodeException e) { System.err.println(String.format("Internal error, translating %s, line %d\nStack trace:", currentFileName, currentUnit.getLineNumber(e.getSourcePosition()))); nErrors++; e.getCause().printStackTrace(System.err); } /** * Report a warning during translation. */ public static void warning(String message) { System.err.println("warning: " + message); if (Options.treatWarningsAsErrors()) { nErrors++; } else { nWarnings++; } } @VisibleForTesting static void resetWarnings() { nWarnings = 0; } @VisibleForTesting static void resetErrors() { nErrors = 0; } /** * Report an error with a specific AST node. */ public static void error(ASTNode node, String message) { int line = getNodeLine(node); error(String.format("%s:%s: %s", currentFileName, line, message)); } /** * Report a warning with a specific AST node. */ public static void warning(ASTNode node, String message) { int line = getNodeLine(node); warning(String.format("%s:%s: %s", currentFileName, line, message)); } private int getCurrentErrorLevel() { return Options.treatWarningsAsErrors() ? nErrors + nWarnings : nErrors; } private static int getNodeLine(ASTNode node) { CompilationUnit unit = (CompilationUnit) node.getRoot(); return unit.getLineNumber(node.getStartPosition()); } private static void loadDeadCodeMap() { DeadCodeMap map = null; File file = Options.getProGuardUsageFile(); if (file != null) { try { map = ProGuardUsageParser.parse(Files.newReaderSupplier(file, Charset.defaultCharset())); } catch (IOException e) { throw new AssertionError(e); } } Options.setDeadCodeMap(map); } private static void loadMappingFiles() { for (String resourceName : Options.getMappingFiles()) { Properties mappings = new Properties(); try { File f = new File(resourceName); if (f.exists()) { FileReader reader = new FileReader(f); try { mappings.load(reader); } finally { reader.close(); } } else { InputStream stream = J2ObjC.class.getResourceAsStream(resourceName); if (stream == null) { error(resourceName + " not found"); } else { try { mappings.load(stream); } finally { stream.close(); } } } } catch (IOException e) { throw new AssertionError(e); } Enumeration<?> keyIterator = mappings.propertyNames(); while (keyIterator.hasMoreElements()) { String javaMethod = (String) keyIterator.nextElement(); String iosMethod = mappings.getProperty(javaMethod); Options.getMethodMappings().put(javaMethod, iosMethod); } } } @VisibleForTesting static void reset() { nErrors = 0; nWarnings = 0; nFiles = 0; currentFileName = null; currentUnit = null; } public static int getErrorCount() { return nErrors; } public static int getWarningCount() { return nWarnings; } private static void exit() { printInfo(String.format("Translated %d %s: %d errors, %d warnings", nFiles, nFiles == 1 ? "file" : "files", nErrors, nWarnings)); Options.deleteTemporaryDirectory(); System.exit(nErrors); } private static void printInfo(String msg) { if (logger.getLevel().intValue() <= Level.INFO.intValue()) { System.out.println(msg); } } /** * Prints time spent in each translation step. Values are in milliseconds, but displayed * as fractional seconds. */ private static void printTimingInfo(long read, long compile, long translate, long write, long total) { if (logger.getLevel().intValue() <= Level.FINE.intValue()) { System.out.println( String.format("time: read=%.3f compile=%.3f translate=%.3f write=%.3f total=%.3f", inSeconds(read), inSeconds(compile), inSeconds(translate), inSeconds(write), inSeconds(total))); } } private static float inSeconds(long milliseconds) { return (float) milliseconds / 1000; } public static String getFileHeader(String sourceFileName) { // Template parameters are: source file, user name, date. String username = System.getProperty("user.name"); Date now = new Date(); String generationDate = DateFormat.getDateInstance(DateFormat.SHORT).format(now); return String.format(Options.getFileHeader(), sourceFileName, username, generationDate); } private static class JarFileLoader extends URLClassLoader { public JarFileLoader() { super(new URL[]{}); } public void addJarFile(String path) throws MalformedURLException { String urlPath = "jar:file://" + path + "!/"; addURL(new URL(urlPath)); } } private static void initPlugins(String[] pluginPaths, String pluginOptionString) throws IOException { @SuppressWarnings("resource") JarFileLoader classLoader = new JarFileLoader(); for (String path : pluginPaths) { if (path.endsWith(".jar")) { JarInputStream jarStream = null; try { jarStream = new JarInputStream(new FileInputStream(path)); classLoader.addJarFile(new File(path).getAbsolutePath()); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { String entryName = entry.getName(); if (!entryName.endsWith(".class")) { continue; } String className = entryName.replaceAll("/", "\\.").substring(0, entryName.length() - ".class".length()); try { Class<?> clazz = classLoader.loadClass(className); if (Plugin.class.isAssignableFrom(clazz)) { Constructor<?> cons = clazz.getDeclaredConstructor(); Plugin plugin = (Plugin) cons.newInstance(); plugin.initPlugin(pluginOptionString); Options.getPlugins().add(plugin); } } catch (Exception e) { throw new IOException("plugin exception: ", e); } } } finally { if (jarStream != null) { jarStream.close(); } } } else { logger.warning("Don't understand plugin path entry: " + path); } } } public static void error(Exception e) { logger.log(Level.SEVERE, "Exiting due to exception", e); System.exit(1); } /** * Entry point for tool. * * @param args command-line arguments: flags and source file names * @throws IOException */ public static void main(String[] args) { if (args.length == 0) { Options.help(true); } String[] files = null; try { files = Options.load(args); if (files.length == 0) { Options.usage("no source files"); } } catch (IOException e) { error(e.getMessage()); System.exit(1); } J2ObjC compiler = new J2ObjC(); try { initPlugins(Options.getPluginPathEntries(), Options.getPluginOptionString()); } catch (IOException e) { error(e); } // Remove dead-code first, so modified file paths are replaced in the // translation list. int beginningErrorLevel = compiler.getCurrentErrorLevel(); try { files = compiler.removeDeadCode(files); } catch (IOException e) { error(e.getMessage()); } if (compiler.getCurrentErrorLevel() > beginningErrorLevel) { return; } nFiles = 0; for (int i = 0; i < files.length; i++) { String file = files[i]; try { if (file.endsWith(".java")) { // Eclipse may send all project entities. printInfo("translating " + file); compiler.translate(file); nFiles++; } else if (file.endsWith(".jar")) { translateSourceJar(compiler, file); } else if (file.startsWith("@")) { translateAtFile(compiler, file.substring(1)); } } catch (IOException e) { error(e.getMessage()); } } for (Plugin plugin : Options.getPlugins()) { plugin.endProcessing(Options.getOutputDirectory()); } exit(); } }
translator/src/main/java/com/google/devtools/j2objc/J2ObjC.java
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.j2objc; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.collect.Lists; import com.google.common.io.CharStreams; import com.google.common.io.Files; import com.google.devtools.j2objc.gen.ObjectiveCHeaderGenerator; import com.google.devtools.j2objc.gen.ObjectiveCImplementationGenerator; import com.google.devtools.j2objc.gen.ObjectiveCSegmentedHeaderGenerator; import com.google.devtools.j2objc.translate.AnonymousClassConverter; import com.google.devtools.j2objc.translate.ArrayRewriter; import com.google.devtools.j2objc.translate.Autoboxer; import com.google.devtools.j2objc.translate.DeadCodeEliminator; import com.google.devtools.j2objc.translate.DestructorGenerator; import com.google.devtools.j2objc.translate.GwtConverter; import com.google.devtools.j2objc.translate.InitializationNormalizer; import com.google.devtools.j2objc.translate.InnerClassExtractor; import com.google.devtools.j2objc.translate.JavaToIOSMethodTranslator; import com.google.devtools.j2objc.translate.JavaToIOSTypeConverter; import com.google.devtools.j2objc.translate.OuterReferenceFixer; import com.google.devtools.j2objc.translate.OuterReferenceResolver; import com.google.devtools.j2objc.translate.Rewriter; import com.google.devtools.j2objc.translate.TypeSorter; import com.google.devtools.j2objc.types.Types; import com.google.devtools.j2objc.util.ASTNodeException; import com.google.devtools.j2objc.util.DeadCodeMap; import com.google.devtools.j2objc.util.NameTable; import com.google.devtools.j2objc.util.ProGuardUsageParser; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.text.DateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; /** * Translation tool for generating Objective C source files from Java sources. * This tool is not intended to be a general purpose converter, but instead is * focused on what is needed for business logic libraries written in Java to * run natively on iOS. In particular, no attempt is made to translate Java * UI framework code to any iOS frameworks. * * @author Tom Ball */ public class J2ObjC { private static String currentFileName; private static CompilationUnit currentUnit; private static int nFiles = 0; private static int nErrors = 0; private static int nWarnings = 0; public enum Language { OBJECTIVE_C(".m"), OBJECTIVE_CPP(".mm"); private final String suffix; private Language(String suffix) { this.suffix = suffix; } public String getSuffix() { return suffix; } } static { // Always enable assertions in translator. ClassLoader loader = J2ObjC.class.getClassLoader(); if (loader != null) { loader.setPackageAssertionStatus(J2ObjC.class.getPackage().getName(), true); } } private static final Logger logger = Logger.getLogger(J2ObjC.class.getName()); /** * Parse a specified Java source file and generate Objective C header(s) * and implementation file(s) from it. * * @param filename the source file to translate */ void translate(String filename) throws IOException { long startTime = System.currentTimeMillis(); int beginningErrorLevel = getCurrentErrorLevel(); logger.finest("reading " + filename); // Read file currentFileName = filename; String source = getSource(filename); if (source == null) { error("no such file: " + filename); return; } long readTime = System.currentTimeMillis(); // Parse and resolve source currentUnit = parse(filename, source); long compileTime = System.currentTimeMillis(); if (getCurrentErrorLevel() > beginningErrorLevel) { return; // Continue to next file. } logger.finest("translating " + filename); long translateTime = 0L; initializeTranslation(currentUnit); try { String newSource = translate(currentUnit, source); translateTime = System.currentTimeMillis(); if (currentUnit.types().isEmpty()) { logger.finest("skipping dead file " + filename); } else { if (Options.printConvertedSources()) { saveConvertedSource(filename, newSource); } logger.finest( "writing output file(s) to " + Options.getOutputDirectory().getAbsolutePath()); // write header if (Options.generateSegmentedHeaders()) { ObjectiveCSegmentedHeaderGenerator.generate(filename, source, currentUnit); } else { ObjectiveCHeaderGenerator.generate(filename, source, currentUnit); } // write implementation file ObjectiveCImplementationGenerator.generate( filename, Options.getLanguage(), currentUnit, source); } } catch (ASTNodeException e) { error(e); } finally { cleanup(); } long endTime = System.currentTimeMillis(); printTimingInfo(readTime - startTime, compileTime - readTime, translateTime - compileTime, endTime - translateTime, endTime - startTime); } private static CompilationUnit parse(String filename, String source) { logger.finest("parsing " + filename); ASTParser parser = ASTParser.newParser(AST.JLS4); Map<String, String> compilerOptions = Options.getCompilerOptions(); parser.setCompilerOptions(compilerOptions); parser.setSource(source.toCharArray()); parser.setResolveBindings(true); setPaths(parser); parser.setUnitName(filename); CompilationUnit unit = (CompilationUnit) parser.createAST(null); for (IProblem problem : getCompilationErrors(unit)) { if (problem.isError()) { error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage())); } } return unit; } private static List<IProblem> getCompilationErrors(CompilationUnit unit) { List<IProblem> errors = Lists.newArrayList(); for (IProblem problem : unit.getProblems()) { if (problem.isError()) { if (((problem.getID() & IProblem.ImportRelated) > 0) && Options.ignoreMissingImports()) { continue; } else { errors.add(problem); } } } return errors; } private void cleanup() { NameTable.cleanup(); Types.cleanup(); OuterReferenceResolver.cleanup(); } /** * Removes dead types and methods, declared in a dead code map. * * @param unit the compilation unit created by ASTParser * @param source the Java source used by ASTParser * @return the rewritten source * @throws AssertionError if the dead code eliminator makes invalid edits */ public static String removeDeadCode(CompilationUnit unit, String source) { if (Options.getDeadCodeMap() == null) { return source; } logger.finest("removing dead code"); new DeadCodeEliminator(Options.getDeadCodeMap()).run(unit); Document doc = new Document(source); TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions()); try { edit.apply(doc); } catch (MalformedTreeException e) { throw new AssertionError(e); } catch (BadLocationException e) { throw new AssertionError(e); } return doc.get(); } private String[] removeDeadCode(String[] files) throws IOException { loadDeadCodeMap(); if (Options.getDeadCodeMap() != null) { for (int i = 0; i < files.length; i++) { String filename = files[i]; logger.finest("reading " + filename); if (filename.endsWith(".java")) { // Read file String source = getSource(filename); if (source == null) { error("no such file: " + filename); return files; } String newPath = removeDeadCode(filename, source); if (!filename.equals(newPath)) { files[i] = newPath; } } else if (filename.endsWith(".jar")) { File f = new File(filename); if (f.exists() && f.isFile()) { ZipFile zfile = new ZipFile(f); try { Enumeration<? extends ZipEntry> enumerator = zfile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); String path = entry.getName(); if (path.endsWith(".java")) { removeDeadCode(path, getSource(path)); } } } finally { zfile.close(); // Also closes input stream. } } } } } Options.insertSourcePath(0, Options.getTemporaryDirectory()); return files; } private String removeDeadCode(String path, String source) throws IOException { long startTime = System.currentTimeMillis(); int beginningErrorLevel = getCurrentErrorLevel(); // Parse and resolve source CompilationUnit unit = parse(path, source); if (getCurrentErrorLevel() > beginningErrorLevel) { return path; } initializeTranslation(unit); String newSource = removeDeadCode(unit, source); if (!newSource.equals(source)) { // Save the new source to the tmpdir and update the files list. String pkg = unit.getPackage().getName().getFullyQualifiedName(); File packageDir = new File(Options.getTemporaryDirectory(), pkg.replace('.', File.separatorChar)); packageDir.mkdirs(); int index = path.lastIndexOf(File.separatorChar); String outputName = index >= 0 ? path.substring(index + 1) : path; File outFile = new File(packageDir, outputName); Files.write(newSource, outFile, Charsets.UTF_8); path = outFile.getAbsolutePath(); } long elapsedTime = System.currentTimeMillis() - startTime; if (logger.getLevel().intValue() <= Level.FINE.intValue()) { System.out.println( String.format("dead-code elimination time: %.3f", inSeconds(elapsedTime))); } return path; } /** * Translates a parsed source file, modifying the compilation unit by * substituting core Java type and method references with iOS equivalents. * For example, <code>java.lang.Object</code> maps to <code>NSObject</code>, * and <code>java.lang.String</code> to <code>NSString</code>. The source is * also modified to add support for iOS memory management, extract inner * classes, etc. * <p> * Note: the returned source file doesn't need to be re-parsed, since the * compilation unit already reflects the changes (it's useful, though, * for dumping intermediate stages). * </p> * * @param unit the compilation unit created by ASTParser * @param source the Java source used by ASTParser * @return the rewritten source * @throws AssertionError if the translator makes invalid edits */ public static String translate(CompilationUnit unit, String source) { // Update code that has GWT references. new GwtConverter().run(unit); // Modify AST to be more compatible with Objective C new Rewriter().run(unit); // Add auto-boxing conversions. new Autoboxer(unit.getAST()).run(unit); // Extract inner and anonymous classes new AnonymousClassConverter(unit).run(unit); new InnerClassExtractor(unit).run(unit); // Normalize init statements new InitializationNormalizer().run(unit); // Fix references to outer scope and captured variables. new OuterReferenceFixer().run(unit); // Translate core Java type use to similar iOS types new JavaToIOSTypeConverter().run(unit); Map<String, String> methodMappings = Options.getMethodMappings(); if (methodMappings.isEmpty()) { // Method maps are loaded here so tests can call translate() directly. loadMappingFiles(); } new JavaToIOSMethodTranslator(unit.getAST(), methodMappings).run(unit); new ArrayRewriter().run(unit); // Reorders the types so that superclasses are declared before classes that // extend them. TypeSorter.sortTypes(unit); // Add dealloc/finalize method(s), if necessary. This is done // after inner class extraction, so that each class releases // only its own instance variables. new DestructorGenerator().run(unit); for (Plugin plugin : Options.getPlugins()) { plugin.processUnit(unit); } // Verify all modified nodes have type bindings Types.verifyNode(unit); Document doc = new Document(source); TextEdit edit = unit.rewrite(doc, Options.getCompilerOptions()); try { edit.apply(doc); } catch (MalformedTreeException e) { throw new AssertionError(e); } catch (BadLocationException e) { throw new AssertionError(e); } return doc.get(); } public static void initializeTranslation(CompilationUnit unit) { unit.recordModifications(); NameTable.initialize(unit); Types.initialize(unit); OuterReferenceResolver.resolve(unit); } private void saveConvertedSource(String filename, String content) { try { File outputFile = new File(Options.getOutputDirectory(), filename); outputFile.getParentFile().mkdirs(); Files.write(content, outputFile, Charset.defaultCharset()); } catch (IOException e) { error(e.getMessage()); } } private static void setPaths(ASTParser parser) { // Add existing boot classpath after declared path, so that core files // referenced, but not being translated, are included. This only matters // when compiling the JRE emulation library sources. List<String> fullClasspath = Lists.newArrayList(); String[] classpathEntries = Options.getClassPathEntries(); for (int i = 0; i < classpathEntries.length; i++) { fullClasspath.add(classpathEntries[i]); } String bootclasspath = Options.getBootClasspath(); for (String path : bootclasspath.split(":")) { // JDT requires that all path elements exist and can hold class files. File f = new File(path); if (f.exists() && (f.isDirectory() || path.endsWith(".jar"))) { fullClasspath.add(path); } } parser.setEnvironment(fullClasspath.toArray(new String[0]), Options.getSourcePathEntries(), Options.getFileEncodings(), true); // Workaround for ASTParser.setEnvironment() bug, which ignores its // last parameter. This has been fixed in the Eclipse post-3.7 Java7 // branch. try { Field field = parser.getClass().getDeclaredField("bits"); field.setAccessible(true); int bits = field.getInt(parser); // Turn off CompilationUnitResolver.INCLUDE_RUNNING_VM_BOOTCLASSPATH bits &= ~0x20; field.setInt(parser, bits); } catch (Exception e) { // should never happen, since only the one known class is manipulated e.printStackTrace(); System.exit(1); } } private String getSource(String path) throws IOException { File file = findSourceFile(path); if (file == null) { return findArchivedSource(path); } else { return Files.toString(file, Charset.defaultCharset()); } } private File findSourceFile(String filename) { File f = getFileOrNull(filename); if (f != null) { return f; } for (String pathEntry : Options.getSourcePathEntries()) { f = getFileOrNull(pathEntry + File.separatorChar + filename); if (f != null) { return f; } } return null; } private String findArchivedSource(String path) throws IOException { for (String pathEntry : Options.getSourcePathEntries()) { File f = new File(pathEntry); if (f.exists() && f.isFile()) { ZipFile zfile; try { zfile = new ZipFile(f); } catch (ZipException e) { // Not a zip or jar file, so skip it. continue; } ZipEntry entry = zfile.getEntry(path); if (entry == null) { continue; } try { Reader in = new InputStreamReader(zfile.getInputStream(entry)); return CharStreams.toString(in); } finally { zfile.close(); // Also closes input stream. } } } return null; } private File getFileOrNull(String fileName) { File f = new File(fileName); return f.exists() ? f : null; } private static void translateSourceJar(J2ObjC compiler, String jarPath) throws IOException { File f = new File(jarPath); if (f.exists() && f.isFile()) { ZipFile zfile = new ZipFile(f); try { Enumeration<? extends ZipEntry> enumerator = zfile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); String path = entry.getName(); if (path.endsWith(".java")) { printInfo("translating " + path); compiler.translate(path); nFiles++; } } } catch (ZipException e) { // Not a zip or jar file, so skip it. return; } finally { zfile.close(); // Also closes input stream. } } } /** * Report an error during translation. */ public static void error(String message) { System.err.println("error: " + message); error(); } /** * Increment the error counter, but don't display an error diagnostic. * This should only be directly called via tests that are testing * error conditions. */ public static void error() { nErrors++; } /** * Report an ASTVisitor error. */ public static void error(ASTNodeException e) { System.err.println(String.format("Internal error, translating %s, line %d\nStack trace:", currentFileName, currentUnit.getLineNumber(e.getSourcePosition()))); nErrors++; e.getCause().printStackTrace(System.err); } /** * Report a warning during translation. */ public static void warning(String message) { System.err.println("warning: " + message); if (Options.treatWarningsAsErrors()) { nErrors++; } else { nWarnings++; } } @VisibleForTesting static void resetWarnings() { nWarnings = 0; } @VisibleForTesting static void resetErrors() { nErrors = 0; } /** * Report an error with a specific AST node. */ public static void error(ASTNode node, String message) { int line = getNodeLine(node); error(String.format("%s:%s: %s", currentFileName, line, message)); } /** * Report a warning with a specific AST node. */ public static void warning(ASTNode node, String message) { int line = getNodeLine(node); warning(String.format("%s:%s: %s", currentFileName, line, message)); } private int getCurrentErrorLevel() { return Options.treatWarningsAsErrors() ? nErrors + nWarnings : nErrors; } private static int getNodeLine(ASTNode node) { CompilationUnit unit = (CompilationUnit) node.getRoot(); return unit.getLineNumber(node.getStartPosition()); } private static void loadDeadCodeMap() { DeadCodeMap map = null; File file = Options.getProGuardUsageFile(); if (file != null) { try { map = ProGuardUsageParser.parse(Files.newReaderSupplier(file, Charset.defaultCharset())); } catch (IOException e) { throw new AssertionError(e); } } Options.setDeadCodeMap(map); } private static void loadMappingFiles() { for (String resourceName : Options.getMappingFiles()) { Properties mappings = new Properties(); try { File f = new File(resourceName); if (f.exists()) { FileReader reader = new FileReader(f); try { mappings.load(reader); } finally { reader.close(); } } else { InputStream stream = J2ObjC.class.getResourceAsStream(resourceName); if (stream == null) { error(resourceName + " not found"); } else { try { mappings.load(stream); } finally { stream.close(); } } } } catch (IOException e) { throw new AssertionError(e); } Enumeration<?> keyIterator = mappings.propertyNames(); while (keyIterator.hasMoreElements()) { String javaMethod = (String) keyIterator.nextElement(); String iosMethod = mappings.getProperty(javaMethod); Options.getMethodMappings().put(javaMethod, iosMethod); } } } @VisibleForTesting static void reset() { nErrors = 0; nWarnings = 0; nFiles = 0; currentFileName = null; currentUnit = null; } public static int getErrorCount() { return nErrors; } public static int getWarningCount() { return nWarnings; } private static void exit() { printInfo(String.format("Translated %d %s: %d errors, %d warnings", nFiles, nFiles == 1 ? "file" : "files", nErrors, nWarnings)); Options.deleteTemporaryDirectory(); System.exit(nErrors); } private static void printInfo(String msg) { if (logger.getLevel().intValue() <= Level.INFO.intValue()) { System.out.println(msg); } } /** * Prints time spent in each translation step. Values are in milliseconds, but displayed * as fractional seconds. */ private static void printTimingInfo(long read, long compile, long translate, long write, long total) { if (logger.getLevel().intValue() <= Level.FINE.intValue()) { System.out.println( String.format("time: read=%.3f compile=%.3f translate=%.3f write=%.3f total=%.3f", inSeconds(read), inSeconds(compile), inSeconds(translate), inSeconds(write), inSeconds(total))); } } private static float inSeconds(long milliseconds) { return (float) milliseconds / 1000; } public static String getFileHeader(String sourceFileName) { // Template parameters are: source file, user name, date. String username = System.getProperty("user.name"); Date now = new Date(); String generationDate = DateFormat.getDateInstance(DateFormat.SHORT).format(now); return String.format(Options.getFileHeader(), sourceFileName, username, generationDate); } private static class JarFileLoader extends URLClassLoader { public JarFileLoader() { super(new URL[]{}); } public void addJarFile(String path) throws MalformedURLException { String urlPath = "jar:file://" + path + "!/"; addURL(new URL(urlPath)); } } private static void initPlugins(String[] pluginPaths, String pluginOptionString) throws IOException { @SuppressWarnings("resource") JarFileLoader classLoader = new JarFileLoader(); for (String path : pluginPaths) { if (path.endsWith(".jar")) { JarInputStream jarStream = null; try { jarStream = new JarInputStream(new FileInputStream(path)); classLoader.addJarFile(new File(path).getAbsolutePath()); JarEntry entry; while ((entry = jarStream.getNextJarEntry()) != null) { String entryName = entry.getName(); if (!entryName.endsWith(".class")) { continue; } String className = entryName.replaceAll("/", "\\.").substring(0, entryName.length() - ".class".length()); try { Class<?> clazz = classLoader.loadClass(className); if (Plugin.class.isAssignableFrom(clazz)) { Constructor<?> cons = clazz.getDeclaredConstructor(); Plugin plugin = (Plugin) cons.newInstance(); plugin.initPlugin(pluginOptionString); Options.getPlugins().add(plugin); } } catch (Exception e) { throw new IOException("plugin exception: ", e); } } } finally { if (jarStream != null) { jarStream.close(); } } } else { logger.warning("Don't understand plugin path entry: " + path); } } } public static void error(Exception e) { logger.log(Level.SEVERE, "Exiting due to exception", e); System.exit(1); } /** * Entry point for tool. * * @param args command-line arguments: flags and source file names * @throws IOException */ public static void main(String[] args) { if (args.length == 0) { Options.help(true); } String[] files = null; try { files = Options.load(args); if (files.length == 0) { Options.usage("no source files"); } } catch (IOException e) { error(e.getMessage()); System.exit(1); } J2ObjC compiler = new J2ObjC(); try { initPlugins(Options.getPluginPathEntries(), Options.getPluginOptionString()); } catch (IOException e) { error(e); } // Remove dead-code first, so modified file paths are replaced in the // translation list. int beginningErrorLevel = compiler.getCurrentErrorLevel(); try { files = compiler.removeDeadCode(files); } catch (IOException e) { error(e.getMessage()); } if (compiler.getCurrentErrorLevel() > beginningErrorLevel) { return; } nFiles = 0; for (int i = 0; i < files.length; i++) { String file = files[i]; try { if (file.endsWith(".java")) { // Eclipse may send all project entities. printInfo("translating " + file); compiler.translate(file); nFiles++; } else if (file.endsWith(".jar")) { translateSourceJar(compiler, file); } } catch (IOException e) { error(e.getMessage()); } } for (Plugin plugin : Options.getPlugins()) { plugin.endProcessing(Options.getOutputDirectory()); } exit(); } }
Added support for @files, files with lists of source paths to translate. Change on 2013/06/18 by tball <[email protected]> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=48177043
translator/src/main/java/com/google/devtools/j2objc/J2ObjC.java
Added support for @files, files with lists of source paths to translate. Change on 2013/06/18 by tball <[email protected]> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=48177043
<ide><path>ranslator/src/main/java/com/google/devtools/j2objc/J2ObjC.java <ide> } <ide> <ide> /** <add> * Translate files listed in a manifest file. <add> */ <add> private static void translateAtFile(J2ObjC compiler, String atFile) throws IOException { <add> if (atFile.isEmpty()) { <add> error("no @ file specified"); <add> exit(); <add> } <add> File f = new File(atFile); <add> if (!f.exists()) { <add> error("no such file: " + atFile); <add> exit(); <add> } <add> String fileList = compiler.getSource(atFile); <add> String[] files = fileList.split("\\s+"); // Split on any whitespace. <add> for (String file : files) { <add> printInfo("translating " + file); <add> compiler.translate(file); <add> nFiles++; <add> } <add> } <add> <add> /** <ide> * Report an error during translation. <ide> */ <ide> public static void error(String message) { <ide> nFiles++; <ide> } else if (file.endsWith(".jar")) { <ide> translateSourceJar(compiler, file); <add> } else if (file.startsWith("@")) { <add> translateAtFile(compiler, file.substring(1)); <ide> } <ide> } catch (IOException e) { <ide> error(e.getMessage());
JavaScript
agpl-3.0
c80a28d1ce83989ba4842da1da2aa801c321e98e
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
a77d5996-2e62-11e5-9284-b827eb9e62be
helloWorld.js
a777e664-2e62-11e5-9284-b827eb9e62be
a77d5996-2e62-11e5-9284-b827eb9e62be
helloWorld.js
a77d5996-2e62-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>a777e664-2e62-11e5-9284-b827eb9e62be <add>a77d5996-2e62-11e5-9284-b827eb9e62be
Java
agpl-3.0
6e2dfdabea1363de58388ee973fb7a2807a66079
0
ua-eas/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kuali/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,kkronenb/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,kuali/kfs,UniversityOfHawaii/kfs,kkronenb/kfs,UniversityOfHawaii/kfs,smith750/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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/ecl1.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.module.purap.service.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.kuali.core.util.KualiDecimal; import org.kuali.core.util.ObjectUtils; import org.kuali.kfs.bo.AccountingLineBase; import org.kuali.kfs.bo.SourceAccountingLine; import org.kuali.kfs.context.SpringContext; import org.kuali.module.purap.bo.PurApAccountingLine; import org.kuali.module.purap.bo.PurApItem; import org.kuali.module.purap.bo.PurApSummaryItem; import org.kuali.module.purap.dao.PurApAccountingDao; import org.kuali.module.purap.document.PaymentRequestDocument; import org.kuali.module.purap.document.PurchasingAccountsPayableDocument; import org.kuali.module.purap.service.PurapAccountingService; import org.kuali.module.purap.service.PurapService; import org.kuali.module.purap.util.PurApItemUtils; import org.kuali.module.purap.util.PurApObjectUtils; import org.kuali.module.purap.util.SummaryAccount; import org.springframework.transaction.annotation.Transactional; @Transactional public class PurapAccountingServiceImpl implements PurapAccountingService { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurapAccountingServiceImpl.class); private static final BigDecimal ONE_HUNDRED = new BigDecimal(100); private static final int SCALE = 340; private static final int BIG_DECIMAL_ROUNDING_MODE = BigDecimal.ROUND_HALF_UP; // local constants private static final Boolean ITEM_TYPES_INCLUDED_VALUE = Boolean.TRUE;; private static final Boolean ITEM_TYPES_EXCLUDED_VALUE = Boolean.FALSE; private static final Boolean ZERO_TOTALS_RETURNED_VALUE = Boolean.TRUE; private static final Boolean ZERO_TOTALS_NOT_RETURNED_VALUE = Boolean.FALSE; private static final Boolean ALTERNATE_AMOUNT_USED = Boolean.TRUE; private static final Boolean ALTERNATE_AMOUNT_NOT_USED = Boolean.FALSE; // Spring injection PurApAccountingDao purApAccountingDao; // below works perfectly for ROUND_HALF_UP private BigDecimal getLowestPossibleRoundUpNumber() { BigDecimal startingDigit = new BigDecimal(0.5); if (SCALE != 0) { startingDigit = startingDigit.movePointLeft(SCALE); } return startingDigit; } private void throwRuntimeException(String methodName, String errorMessage) { LOG.error(methodName + " " + errorMessage); throw new RuntimeException(errorMessage); } /** * @deprecated * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List, org.kuali.core.util.KualiDecimal, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts, KualiDecimal totalAmount, Integer percentScale) { //TODO: remove this method, use the class one below return null;//generateAccountDistributionForProration(accounts, totalAmount, percentScale, null); } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List, org.kuali.core.util.KualiDecimal, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts, KualiDecimal totalAmount, Integer percentScale, Class clazz) { String methodName = "generateAccountDistributionForProration()"; LOG.debug(methodName + " started"); List<PurApAccountingLine> newAccounts = new ArrayList(); if (totalAmount.isZero()) { throwRuntimeException(methodName,"Purchasing/Accounts Payable account distribution for proration does not allow zero dollar total."); //TODO: check with David is this ok?! // generateAccountDistributionForProrationWithZeroTotal(accounts, percentScale); } BigDecimal percentTotal = BigDecimal.ZERO; BigDecimal totalAmountBigDecimal = totalAmount.bigDecimalValue(); for(SourceAccountingLine accountingLine : accounts) { LOG.debug(methodName + " " + accountingLine.getAccountNumber() + " " + accountingLine.getAmount() + "/" + totalAmountBigDecimal); //TODO: Chris - is this scale ok? BigDecimal pct = accountingLine.getAmount().bigDecimalValue().divide(totalAmountBigDecimal,percentScale,BIG_DECIMAL_ROUNDING_MODE); pct = pct.multiply(ONE_HUNDRED).stripTrailingZeros(); LOG.debug(methodName + " pct = " + pct + " (trailing zeros removed)"); BigDecimal lowestPossible = this.getLowestPossibleRoundUpNumber(); if (lowestPossible.compareTo(pct) <= 0) { PurApAccountingLine newAccountingLine; newAccountingLine = null; try { newAccountingLine = (PurApAccountingLine)clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine); newAccountingLine.setAccountLinePercent(pct); LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent()); newAccounts.add(newAccountingLine); percentTotal = percentTotal.add(newAccountingLine.getAccountLinePercent()); LOG.debug(methodName + " total = " + percentTotal); } } if ((percentTotal.compareTo(BigDecimal.ZERO)) == 0) { /* This means there are so many accounts or so strange a distribution * that we can't round properly... not sure of viable solution */ throwRuntimeException(methodName, "Can't round properly due to number of accounts"); } // Now deal with rounding if ((ONE_HUNDRED.compareTo(percentTotal)) < 0) { /* The total percent is greater than one hundred * * Here we find the account that occurs latest in our list with a percent * that is higher than the difference and we subtract off the difference */ BigDecimal difference = percentTotal.subtract(ONE_HUNDRED); LOG.debug(methodName + " Rounding up by " + difference); boolean foundAccountToUse = false; int currentNbr = newAccounts.size() - 1; while ( currentNbr >= 0 ) { PurApAccountingLine potentialSlushAccount = (PurApAccountingLine)newAccounts.get(currentNbr); if ((difference.compareTo(potentialSlushAccount.getAccountLinePercent())) < 0) { // the difference amount is less than the current accounts percent... use this account // the 'potentialSlushAccount' technically is now the true 'Slush Account' potentialSlushAccount.setAccountLinePercent((potentialSlushAccount.getAccountLinePercent().subtract(difference)).stripTrailingZeros()); foundAccountToUse = true; break; } currentNbr--; } if (!foundAccountToUse) { /* We could not find any account in our list where the percent of that account * was greater than that of the difference... doing so on just any account could * result in a negative percent value */ throwRuntimeException(methodName, "Can't round properly due to math calculation error"); } } else if ((ONE_HUNDRED.compareTo(percentTotal)) > 0) { /* The total percent is less than one hundred * * Here we find the last account in our list and add the remaining required percent * to it's already calculated percent */ BigDecimal difference = ONE_HUNDRED.subtract(percentTotal); LOG.debug(methodName + " Rounding down by " + difference); PurApAccountingLine slushAccount = (PurApAccountingLine)newAccounts.get(newAccounts.size() - 1); slushAccount.setAccountLinePercent((slushAccount.getAccountLinePercent().add(difference)).stripTrailingZeros()); } LOG.debug(methodName + " ended"); return newAccounts; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProrationWithZeroTotal(java.util.List, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProrationWithZeroTotal(List<PurApAccountingLine> accounts, Integer percentScale) { String methodName = "generateAccountDistributionForProrationWithZeroTotal()"; LOG.debug(methodName + " started"); // find the total percent and strip trailing zeros BigDecimal totalPercentValue = BigDecimal.ZERO; for(PurApAccountingLine accountingLine : accounts) { totalPercentValue = (totalPercentValue.add(accountingLine.getAccountLinePercent())).stripTrailingZeros(); } if ((BigDecimal.ZERO.compareTo(totalPercentValue.remainder(ONE_HUNDRED))) != 0) { throwRuntimeException(methodName, "Invalid Percent Total of '" + totalPercentValue + "' does not allow for account distribution (must be multiple of 100)"); } List newAccounts = new ArrayList(); BigDecimal logDisplayOnlyTotal = BigDecimal.ZERO; BigDecimal percentUsed = BigDecimal.ZERO; int accountListSize = accounts.size(); int i = 0; for(PurApAccountingLine accountingLine : accounts) { i++; BigDecimal percentToUse = BigDecimal.ZERO; LOG.debug(methodName + " " + accountingLine.getChartOfAccountsCode() + "-" + accountingLine.getAccountNumber() + " " + accountingLine.getAmount() + "/" + percentToUse); // if it's the last account make up the leftover percent BigDecimal acctPercent = accountingLine.getAccountLinePercent(); if ((i != accountListSize) || (accountListSize == 1)) { // this account is not the last account or there is only one account percentToUse = (acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE)).multiply(ONE_HUNDRED); percentUsed = percentUsed.add(((acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE))).multiply(ONE_HUNDRED)); } else { // this account is the last account so we have to makeup whatever is left out of 100 percentToUse = ONE_HUNDRED.subtract(percentUsed); } PurApAccountingLine newAccountingLine = accountingLine.createBlankAmountsCopy(); LOG.debug(methodName + " pct = " + percentToUse); newAccountingLine.setAccountLinePercent(percentToUse.setScale(accountingLine.getAccountLinePercent().scale(),BIG_DECIMAL_ROUNDING_MODE)); LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent()); newAccounts.add(newAccountingLine); logDisplayOnlyTotal = logDisplayOnlyTotal.add(newAccountingLine.getAccountLinePercent()); LOG.debug(methodName + " total = " + logDisplayOnlyTotal); } LOG.debug(methodName + " ended"); return newAccounts; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummary(java.util.List) */ public List<SourceAccountingLine> generateSummary(List<PurApItem> items) { String methodName = "generateSummary()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } // public Map<SourceAccountingLine, List<PurchasingApItem>> generateSummaryWithItems(List<PurchasingApItem> items) { // String methodName = "generateSummaryWithItems()"; // LOG.debug(methodName + " started"); // Map<SourceAccountingLine, List<PurchasingApItem>> returnList = generateAccountSummaryWithItems(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); // LOG.debug(methodName + " ended"); // return returnList; // } public List<SummaryAccount> generateSummaryAccounts(PurchasingAccountsPayableDocument document) { //always update the amounts first updateAccountAmounts(document); return generateSummaryAccounts(document.getItems()); } private List<SummaryAccount> generateSummaryAccounts(List<PurApItem> items) { String methodName = "generateSummaryAccounts()"; List<SummaryAccount> returnList = new ArrayList<SummaryAccount>(); LOG.debug(methodName + " started"); List<SourceAccountingLine> sourceLines = generateSummary(items); for (SourceAccountingLine sourceAccountingLine : sourceLines) { SummaryAccount summaryAccount = new SummaryAccount(); summaryAccount.setAccount((SourceAccountingLine)ObjectUtils.deepCopy(sourceAccountingLine)); for (PurApItem item : items) { List<PurApAccountingLine> itemAccounts = item.getSourceAccountingLines(); for (PurApAccountingLine purApAccountingLine : itemAccounts) { if(purApAccountingLine.accountStringsAreEqual(summaryAccount.getAccount())) { PurApSummaryItem summaryItem = item.getSummaryItem(); summaryItem.setEstimatedEncumberanceAmount(purApAccountingLine.getAmount()); summaryAccount.getItems().add(summaryItem); break; } } } returnList.add(summaryAccount); } LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryWithNoZeroTotals(java.util.List) */ public List<SourceAccountingLine> generateSummaryWithNoZeroTotals(List<PurApItem> items) { String methodName = "generateSummaryWithNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryWithNoZeroTotalsUsingAlternateAmount(java.util.List) */ public List<SourceAccountingLine> generateSummaryWithNoZeroTotalsUsingAlternateAmount(List<PurApItem> items) { String methodName = "generateSummaryWithNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryExcludeItemTypes(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryExcludeItemTypes(List<PurApItem> items, Set excludedItemTypeCodes) { String methodName = "generateSummaryExcludeItemTypes()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, excludedItemTypeCodes, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryIncludeItemTypesAndNoZeroTotals(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryIncludeItemTypesAndNoZeroTotals(List<PurApItem> items, Set includedItemTypeCodes) { String methodName = "generateSummaryExcludeItemTypesAndNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, includedItemTypeCodes, ITEM_TYPES_INCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryIncludeItemTypes(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryIncludeItemTypes(List<PurApItem> items, Set includedItemTypeCodes) { String methodName = "generateSummaryIncludeItemTypes()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, includedItemTypeCodes, ITEM_TYPES_INCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryExcludeItemTypesAndNoZeroTotals(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryExcludeItemTypesAndNoZeroTotals(List<PurApItem> items, Set excludedItemTypeCodes) { String methodName = "generateSummaryIncludeItemTypesAndNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, excludedItemTypeCodes, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } // /** // * This method takes a list of {@link PurchasingApItem} objects and parses through them to see whether each item should be processed. If // * the item is valid to be processed this method will get it's accounts and add the accounts to a summary list. If one single account has // * the same account string variables as an account on another item then the two accounts total amounts will be summed and used as the total // * amount of the {@link SourceAccountingLine} object sent back in the list. // * // * See Also: {@link #getProcessablePurapItems(List, Set, Boolean, Boolean)} // * // * @param items - list of {@link PurchasingApItem} objects that need to be parsed // * @param itemTypeCodes - list of {@link org.kuali.module.purap.bo.ItemType} codes used in conjunction with itemTypeCodesAreIncluded parameter // * @param itemTypeCodesAreIncluded - value to tell whether the itemTypeCodes parameter lists inclusion or exclusion variables (see {@link #ITEM_TYPES_INCLUDED_VALUE}) // * @param useZeroTotals - value to tell whether to include zero dollar items (see {@link #ZERO_TOTALS_RETURNED_VALUE}) // * @return a list of {@link SourceAccountingLine} objects that represent a summing of all accounts across all derived processable items based on given criteria // */ // private Map<SourceAccountingLine, List<PurchasingApItem>> generateAccountSummaryWithItems(List<PurchasingApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals, // Boolean useAlternateAmount) { // Map<SourceAccountingLine, List<PurchasingApItem>>accountItemsMap = new HashMap(); // List<PurchasingApItem> itemsToProcess = getProcessablePurapItems(items, itemTypeCodes, itemTypeCodesAreIncluded, useZeroTotals); // Set<PurApAccountingLine> accountSet = new HashSet<PurApAccountingLine>(); // // for (PurchasingApItem currentItemFromDocument : items) { // if (PurApItemUtils.checkItemActive(currentItemFromDocument)) { // PurchasingApItem copyItemFromDocument = (PurchasingApItem)ObjectUtils.deepCopy(currentItemFromDocument); // for (PurApAccountingLine account : copyItemFromDocument.getSourceAccountingLines()) { // PurchasingApItem currentItem = (PurchasingApItem)ObjectUtils.deepCopy(copyItemFromDocument); // currentItem.setExtendedPriceForAccountSummary(account.getAmount()); // boolean thisAccountAlreadyInSet = false; // for (Iterator iter = accountSet.iterator(); iter.hasNext();) { // PurApAccountingLine alreadyAddedAccount = (PurApAccountingLine) iter.next(); // if (alreadyAddedAccount.accountStringsAreEqual(account)) { // if (useAlternateAmount) { // alreadyAddedAccount.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation().add(account.getAlternateAmountForGLEntryCreation())); // account.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation()); // } // else { // alreadyAddedAccount.setAmount(alreadyAddedAccount.getAmount().add(account.getAmount())); // account.setAmount(alreadyAddedAccount.getAmount()); // } // thisAccountAlreadyInSet = true; // break; // } // } // // PurApAccountingLine accountToAdd = (PurApAccountingLine) ObjectUtils.deepCopy(account); // SourceAccountingLine sourceLine = accountToAdd.generateSourceAccountingLine(); // if (!thisAccountAlreadyInSet) { // accountSet.add(accountToAdd); // if (accountToAdd.isEmpty()) { // String errorMessage = "Found an 'empty' account in summary generation " + accountToAdd.toString(); // LOG.error("generateAccountSummary() " + errorMessage); // throw new RuntimeException(errorMessage); // } // if (useAlternateAmount) { // sourceLine.setAmount(accountToAdd.getAlternateAmountForGLEntryCreation()); // } // List<PurchasingApItem> itemList = new ArrayList(); // itemList.add(currentItem); // accountItemsMap.put(sourceLine, itemList); // } // else { // for (Iterator mapIter = accountItemsMap.keySet().iterator(); mapIter.hasNext();) { // SourceAccountingLine accountFromMap = (SourceAccountingLine)mapIter.next(); // SourceAccountingLine tempAccount = (SourceAccountingLine)ObjectUtils.deepCopy(accountFromMap); // tempAccount.setAmount(sourceLine.getAmount()); // if (sourceLine.toString().equals(tempAccount.toString())) { // accountFromMap.setAmount(sourceLine.getAmount()); // List<PurchasingApItem> itemList = accountItemsMap.get(accountFromMap); // itemList.add(currentItem); // break; // } // } // } // } // } // } // // return accountItemsMap; // } private List<SourceAccountingLine> generateAccountSummary(List<PurApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals, Boolean useAlternateAmount) { List<PurApItem> itemsToProcess = getProcessablePurapItems(items, itemTypeCodes, itemTypeCodesAreIncluded, useZeroTotals); Set<PurApAccountingLine> accountSet = new HashSet<PurApAccountingLine>(); for (PurApItem currentItem : items) { if (PurApItemUtils.checkItemActive(currentItem)) { for (PurApAccountingLine account : currentItem.getSourceAccountingLines()) { boolean thisAccountAlreadyInSet = false; for (Iterator iter = accountSet.iterator(); iter.hasNext();) { PurApAccountingLine alreadyAddedAccount = (PurApAccountingLine) iter.next(); if (alreadyAddedAccount.accountStringsAreEqual(account)) { if (useAlternateAmount) { alreadyAddedAccount.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation().add(account.getAlternateAmountForGLEntryCreation())); } else { alreadyAddedAccount.setAmount(alreadyAddedAccount.getAmount().add(account.getAmount())); } thisAccountAlreadyInSet = true; break; } } if (!thisAccountAlreadyInSet) { PurApAccountingLine accountToAdd = (PurApAccountingLine) ObjectUtils.deepCopy(account); accountSet.add(accountToAdd); } } } } // convert list of PurApAccountingLine objects to SourceAccountingLineObjects List<SourceAccountingLine> sourceAccounts = new ArrayList<SourceAccountingLine>(); for (Iterator iter = accountSet.iterator(); iter.hasNext();) { PurApAccountingLine accountToAlter = (PurApAccountingLine) iter.next(); if (accountToAlter.isEmpty()) { String errorMessage = "Found an 'empty' account in summary generation " + accountToAlter.toString(); LOG.error("generateAccountSummary() " + errorMessage); throw new RuntimeException(errorMessage); } SourceAccountingLine sourceLine = accountToAlter.generateSourceAccountingLine(); if (useAlternateAmount) { sourceLine.setAmount(accountToAlter.getAlternateAmountForGLEntryCreation()); } sourceAccounts.add(sourceLine); } return sourceAccounts; } /** * This method takes a list of {@link PurchasingApItem} objects and parses through them to see if each one should be processed according * the the other variables passed in.<br> * <br> * Example 1:<br> * items = "ITEM", "SITM", "FRHT", "SPHD"<br> * itemTypeCodes = "FRHT"<br> * itemTypeCodesAreIncluded = ITEM_TYPES_EXCLUDED_VALUE<br> * return items "ITEM", "SITM", "FRHT", "SPHD"<br> * <br> * <br> * Example 2:<br> * items = "ITEM", "SITM", "FRHT", "SPHD"<br> * itemTypeCodes = "ITEM","FRHT"<br> * itemTypeCodesAreIncluded = ITEM_TYPES_INCLUDED_VALUE<br> * return items "ITEM", "FRHT"<br> * * @param items - list of {@link PurchasingApItem} objects that need to be parsed * @param itemTypeCodes - list of {@link org.kuali.module.purap.bo.ItemType} codes used in conjunction with itemTypeCodesAreIncluded parameter * @param itemTypeCodesAreIncluded - value to tell whether the itemTypeCodes parameter lists inclusion or exclusion variables (see {@link #ITEM_TYPES_INCLUDED_VALUE}) * @param useZeroTotals - value to tell whether to include zero dollar items (see {@link #ZERO_TOTALS_RETURNED_VALUE}) * @return a list of {@link PurchasingApItem} objects that should be used for processing by calling method */ private List<PurApItem> getProcessablePurapItems(List<PurApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals) { String methodName = "getProcessablePurapItems()"; List<PurApItem> newItemList = new ArrayList<PurApItem>(); // error out if we have an invalid 'itemTypeCodesAreIncluded' value if ( (!(ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded))) && (!(ITEM_TYPES_EXCLUDED_VALUE.equals(itemTypeCodesAreIncluded))) ) { throwRuntimeException(methodName, "Invalid parameter found while trying to find processable items for dealing with purchasing/accounts payable accounts"); } for (PurApItem currentItem : items) { if ( (itemTypeCodes != null) && (!(itemTypeCodes.isEmpty())) ) { // we have at least one entry in our item type code list boolean foundMatchInList = false; // check to see if this item type code is in the list for (Iterator iterator = itemTypeCodes.iterator(); iterator.hasNext();) { String itemTypeCode = (String) iterator.next(); // include this item if it's in the included list if (itemTypeCode.equals(currentItem.getItemType().getItemTypeCode())) { foundMatchInList = true; break; } } // check to see if item type code was found and if the list is describing included or excluded item types if ( (foundMatchInList) && (ITEM_TYPES_EXCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) ) { // this item type code is in the list // this item type code is excluded so we skip it continue; // skips current item } else if ( (!foundMatchInList) && (ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) ) { // this item type code is not in the list // this item type code is not included so we skip it continue; // skips current item } } else { // the item type code list is empty if (ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) { // the item type code list is empty and the list is supposed to contain the item types to include throwRuntimeException(methodName, "Invalid parameter and list of items found while trying to find processable items for dealing with purchasing/accounts payable accounts"); } } //TODO check to see if we should be allowing null in the extendedPrice (hjs) if ( (ZERO_TOTALS_NOT_RETURNED_VALUE.equals(useZeroTotals)) && (ObjectUtils.isNull(currentItem.getExtendedPrice()) || ((KualiDecimal.ZERO.compareTo(currentItem.getExtendedPrice())) == 0)) ) { // if we don't return zero dollar items then skip this one continue; } newItemList.add(currentItem); } return newItemList; } /** * * This method updates account amounts based on the percents. * @param document the document */ public void updateAccountAmounts(PurchasingAccountsPayableDocument document) { //TODO: Chris - this should probably be injected instead of using the locator (or put in doc) also don't forget to update the percent at fiscal approve //don't update if past the AP review level if((document instanceof PaymentRequestDocument) && SpringContext.getBean(PurapService.class).isFullDocumentEntryCompleted(document)){ return; } for (PurApItem item : document.getItems()) { updateItemAccountAmounts(item); } } /** * This method updates a single items account amounts * @param item */ public void updateItemAccountAmounts(PurApItem item) { if ( (item.getExtendedPrice()!=null) && KualiDecimal.ZERO.compareTo(item.getExtendedPrice()) != 0 ) { //TODO: is this the best sort to use? // Collections.sort( (List)item.getSourceAccountingLines() ); KualiDecimal accountTotal = KualiDecimal.ZERO; PurApAccountingLine lastAccount = null; for (PurApAccountingLine account : item.getSourceAccountingLines()) { BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()).divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(item.getExtendedPrice().toString())))); accountTotal = accountTotal.add(account.getAmount()); lastAccount = account; } // put excess on last account if ( lastAccount != null ) { KualiDecimal difference = item.getExtendedPrice().subtract(accountTotal); lastAccount.setAmount(lastAccount.getAmount().add(difference)); } } else { //zero out if extended price is zero for (PurApAccountingLine account : item.getSourceAccountingLines()) { account.setAmount(KualiDecimal.ZERO); } } } public List<PurApAccountingLine> getAccountsFromItem(PurApItem item) { // TODO Auto-generated method stub return purApAccountingDao.getAccountingLinesForItem(item); } /** * Gets the purApAccountingDao attribute. * @return Returns the purApAccountingDao. */ public PurApAccountingDao getPurApAccountingDao() { return purApAccountingDao; } /** * Sets the purApAccountingDao attribute value. * @param purApAccountingDao The purApAccountingDao to set. */ public void setPurApAccountingDao(PurApAccountingDao purApAccountingDao) { this.purApAccountingDao = purApAccountingDao; } }
work/src/org/kuali/kfs/module/purap/service/impl/PurapAccountingServiceImpl.java
/* * Copyright 2006-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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/ecl1.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.module.purap.service.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.kuali.core.util.KualiDecimal; import org.kuali.core.util.ObjectUtils; import org.kuali.kfs.bo.AccountingLineBase; import org.kuali.kfs.bo.SourceAccountingLine; import org.kuali.kfs.context.SpringContext; import org.kuali.module.purap.bo.PurApAccountingLine; import org.kuali.module.purap.bo.PurApItem; import org.kuali.module.purap.bo.PurApSummaryItem; import org.kuali.module.purap.dao.PurApAccountingDao; import org.kuali.module.purap.document.PaymentRequestDocument; import org.kuali.module.purap.document.PurchasingAccountsPayableDocument; import org.kuali.module.purap.document.PurchasingAccountsPayableDocumentBase; import org.kuali.module.purap.service.PurapAccountingService; import org.kuali.module.purap.service.PurapService; import org.kuali.module.purap.util.PurApItemUtils; import org.kuali.module.purap.util.PurApObjectUtils; import org.kuali.module.purap.util.SummaryAccount; import org.springframework.transaction.annotation.Transactional; @Transactional public class PurapAccountingServiceImpl implements PurapAccountingService { private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(PurapAccountingServiceImpl.class); private static final BigDecimal ONE_HUNDRED = new BigDecimal(100); private static final int SCALE = 340; private static final int BIG_DECIMAL_ROUNDING_MODE = BigDecimal.ROUND_HALF_UP; // local constants private static final Boolean ITEM_TYPES_INCLUDED_VALUE = Boolean.TRUE;; private static final Boolean ITEM_TYPES_EXCLUDED_VALUE = Boolean.FALSE; private static final Boolean ZERO_TOTALS_RETURNED_VALUE = Boolean.TRUE; private static final Boolean ZERO_TOTALS_NOT_RETURNED_VALUE = Boolean.FALSE; private static final Boolean ALTERNATE_AMOUNT_USED = Boolean.TRUE; private static final Boolean ALTERNATE_AMOUNT_NOT_USED = Boolean.FALSE; // Spring injection PurApAccountingDao purApAccountingDao; // below works perfectly for ROUND_HALF_UP private BigDecimal getLowestPossibleRoundUpNumber() { BigDecimal startingDigit = new BigDecimal(0.5); if (SCALE != 0) { startingDigit = startingDigit.movePointLeft(SCALE); } return startingDigit; } private void throwRuntimeException(String methodName, String errorMessage) { LOG.error(methodName + " " + errorMessage); throw new RuntimeException(errorMessage); } /** * @deprecated * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List, org.kuali.core.util.KualiDecimal, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts, KualiDecimal totalAmount, Integer percentScale) { //TODO: remove this method, use the class one below return null;//generateAccountDistributionForProration(accounts, totalAmount, percentScale, null); } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProration(java.util.List, org.kuali.core.util.KualiDecimal, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProration(List<SourceAccountingLine> accounts, KualiDecimal totalAmount, Integer percentScale, Class clazz) { String methodName = "generateAccountDistributionForProration()"; LOG.debug(methodName + " started"); List<PurApAccountingLine> newAccounts = new ArrayList(); if (totalAmount.isZero()) { throwRuntimeException(methodName,"Purchasing/Accounts Payable account distribution for proration does not allow zero dollar total."); //TODO: check with David is this ok?! // generateAccountDistributionForProrationWithZeroTotal(accounts, percentScale); } BigDecimal percentTotal = BigDecimal.ZERO; BigDecimal totalAmountBigDecimal = totalAmount.bigDecimalValue(); for(SourceAccountingLine accountingLine : accounts) { LOG.debug(methodName + " " + accountingLine.getAccountNumber() + " " + accountingLine.getAmount() + "/" + totalAmountBigDecimal); //TODO: Chris - is this scale ok? BigDecimal pct = accountingLine.getAmount().bigDecimalValue().divide(totalAmountBigDecimal,percentScale,BIG_DECIMAL_ROUNDING_MODE); pct = pct.multiply(ONE_HUNDRED).stripTrailingZeros(); LOG.debug(methodName + " pct = " + pct + " (trailing zeros removed)"); BigDecimal lowestPossible = this.getLowestPossibleRoundUpNumber(); if (lowestPossible.compareTo(pct) <= 0) { PurApAccountingLine newAccountingLine; newAccountingLine = null; try { newAccountingLine = (PurApAccountingLine)clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } PurApObjectUtils.populateFromBaseClass(AccountingLineBase.class, accountingLine, newAccountingLine); newAccountingLine.setAccountLinePercent(pct); LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent()); newAccounts.add(newAccountingLine); percentTotal = percentTotal.add(newAccountingLine.getAccountLinePercent()); LOG.debug(methodName + " total = " + percentTotal); } } if ((percentTotal.compareTo(BigDecimal.ZERO)) == 0) { /* This means there are so many accounts or so strange a distribution * that we can't round properly... not sure of viable solution */ throwRuntimeException(methodName, "Can't round properly due to number of accounts"); } // Now deal with rounding if ((ONE_HUNDRED.compareTo(percentTotal)) < 0) { /* The total percent is greater than one hundred * * Here we find the account that occurs latest in our list with a percent * that is higher than the difference and we subtract off the difference */ BigDecimal difference = percentTotal.subtract(ONE_HUNDRED); LOG.debug(methodName + " Rounding up by " + difference); boolean foundAccountToUse = false; int currentNbr = newAccounts.size() - 1; while ( currentNbr >= 0 ) { PurApAccountingLine potentialSlushAccount = (PurApAccountingLine)newAccounts.get(currentNbr); if ((difference.compareTo(potentialSlushAccount.getAccountLinePercent())) < 0) { // the difference amount is less than the current accounts percent... use this account // the 'potentialSlushAccount' technically is now the true 'Slush Account' potentialSlushAccount.setAccountLinePercent((potentialSlushAccount.getAccountLinePercent().subtract(difference)).stripTrailingZeros()); foundAccountToUse = true; break; } currentNbr--; } if (!foundAccountToUse) { /* We could not find any account in our list where the percent of that account * was greater than that of the difference... doing so on just any account could * result in a negative percent value */ throwRuntimeException(methodName, "Can't round properly due to math calculation error"); } } else if ((ONE_HUNDRED.compareTo(percentTotal)) > 0) { /* The total percent is less than one hundred * * Here we find the last account in our list and add the remaining required percent * to it's already calculated percent */ BigDecimal difference = ONE_HUNDRED.subtract(percentTotal); LOG.debug(methodName + " Rounding down by " + difference); PurApAccountingLine slushAccount = (PurApAccountingLine)newAccounts.get(newAccounts.size() - 1); slushAccount.setAccountLinePercent((slushAccount.getAccountLinePercent().add(difference)).stripTrailingZeros()); } LOG.debug(methodName + " ended"); return newAccounts; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateAccountDistributionForProrationWithZeroTotal(java.util.List, java.lang.Integer) */ public List<PurApAccountingLine> generateAccountDistributionForProrationWithZeroTotal(List<PurApAccountingLine> accounts, Integer percentScale) { String methodName = "generateAccountDistributionForProrationWithZeroTotal()"; LOG.debug(methodName + " started"); // find the total percent and strip trailing zeros BigDecimal totalPercentValue = BigDecimal.ZERO; for(PurApAccountingLine accountingLine : accounts) { totalPercentValue = (totalPercentValue.add(accountingLine.getAccountLinePercent())).stripTrailingZeros(); } if ((BigDecimal.ZERO.compareTo(totalPercentValue.remainder(ONE_HUNDRED))) != 0) { throwRuntimeException(methodName, "Invalid Percent Total of '" + totalPercentValue + "' does not allow for account distribution (must be multiple of 100)"); } List newAccounts = new ArrayList(); BigDecimal logDisplayOnlyTotal = BigDecimal.ZERO; BigDecimal percentUsed = BigDecimal.ZERO; int accountListSize = accounts.size(); int i = 0; for(PurApAccountingLine accountingLine : accounts) { i++; BigDecimal percentToUse = BigDecimal.ZERO; LOG.debug(methodName + " " + accountingLine.getChartOfAccountsCode() + "-" + accountingLine.getAccountNumber() + " " + accountingLine.getAmount() + "/" + percentToUse); // if it's the last account make up the leftover percent BigDecimal acctPercent = accountingLine.getAccountLinePercent(); if ((i != accountListSize) || (accountListSize == 1)) { // this account is not the last account or there is only one account percentToUse = (acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE)).multiply(ONE_HUNDRED); percentUsed = percentUsed.add(((acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE))).multiply(ONE_HUNDRED)); } else { // this account is the last account so we have to makeup whatever is left out of 100 percentToUse = ONE_HUNDRED.subtract(percentUsed); } PurApAccountingLine newAccountingLine = accountingLine.createBlankAmountsCopy(); LOG.debug(methodName + " pct = " + percentToUse); newAccountingLine.setAccountLinePercent(percentToUse.setScale(accountingLine.getAccountLinePercent().scale(),BIG_DECIMAL_ROUNDING_MODE)); LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent()); newAccounts.add(newAccountingLine); logDisplayOnlyTotal = logDisplayOnlyTotal.add(newAccountingLine.getAccountLinePercent()); LOG.debug(methodName + " total = " + logDisplayOnlyTotal); } LOG.debug(methodName + " ended"); return newAccounts; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummary(java.util.List) */ public List<SourceAccountingLine> generateSummary(List<PurApItem> items) { String methodName = "generateSummary()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } // public Map<SourceAccountingLine, List<PurchasingApItem>> generateSummaryWithItems(List<PurchasingApItem> items) { // String methodName = "generateSummaryWithItems()"; // LOG.debug(methodName + " started"); // Map<SourceAccountingLine, List<PurchasingApItem>> returnList = generateAccountSummaryWithItems(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); // LOG.debug(methodName + " ended"); // return returnList; // } public List<SummaryAccount> generateSummaryAccounts(PurchasingAccountsPayableDocument document) { //always update the amounts first updateAccountAmounts(document); return generateSummaryAccounts(document.getItems()); } private List<SummaryAccount> generateSummaryAccounts(List<PurApItem> items) { String methodName = "generateSummaryAccounts()"; List<SummaryAccount> returnList = new ArrayList<SummaryAccount>(); LOG.debug(methodName + " started"); List<SourceAccountingLine> sourceLines = generateSummary(items); for (SourceAccountingLine sourceAccountingLine : sourceLines) { SummaryAccount summaryAccount = new SummaryAccount(); summaryAccount.setAccount((SourceAccountingLine)ObjectUtils.deepCopy(sourceAccountingLine)); for (PurApItem item : items) { List<PurApAccountingLine> itemAccounts = item.getSourceAccountingLines(); for (PurApAccountingLine purApAccountingLine : itemAccounts) { if(purApAccountingLine.accountStringsAreEqual(summaryAccount.getAccount())) { PurApSummaryItem summaryItem = item.getSummaryItem(); summaryItem.setEstimatedEncumberanceAmount(purApAccountingLine.getAmount()); summaryAccount.getItems().add(summaryItem); break; } } } returnList.add(summaryAccount); } LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryWithNoZeroTotals(java.util.List) */ public List<SourceAccountingLine> generateSummaryWithNoZeroTotals(List<PurApItem> items) { String methodName = "generateSummaryWithNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryWithNoZeroTotalsUsingAlternateAmount(java.util.List) */ public List<SourceAccountingLine> generateSummaryWithNoZeroTotalsUsingAlternateAmount(List<PurApItem> items) { String methodName = "generateSummaryWithNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, null, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryExcludeItemTypes(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryExcludeItemTypes(List<PurApItem> items, Set excludedItemTypeCodes) { String methodName = "generateSummaryExcludeItemTypes()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, excludedItemTypeCodes, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryIncludeItemTypesAndNoZeroTotals(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryIncludeItemTypesAndNoZeroTotals(List<PurApItem> items, Set includedItemTypeCodes) { String methodName = "generateSummaryExcludeItemTypesAndNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, includedItemTypeCodes, ITEM_TYPES_INCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryIncludeItemTypes(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryIncludeItemTypes(List<PurApItem> items, Set includedItemTypeCodes) { String methodName = "generateSummaryIncludeItemTypes()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, includedItemTypeCodes, ITEM_TYPES_INCLUDED_VALUE, ZERO_TOTALS_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } /** * * @see org.kuali.module.purap.service.PurapAccountingService#generateSummaryExcludeItemTypesAndNoZeroTotals(java.util.List, java.util.Set) */ public List<SourceAccountingLine> generateSummaryExcludeItemTypesAndNoZeroTotals(List<PurApItem> items, Set excludedItemTypeCodes) { String methodName = "generateSummaryIncludeItemTypesAndNoZeroTotals()"; LOG.debug(methodName + " started"); List<SourceAccountingLine> returnList = generateAccountSummary(items, excludedItemTypeCodes, ITEM_TYPES_EXCLUDED_VALUE, ZERO_TOTALS_NOT_RETURNED_VALUE, ALTERNATE_AMOUNT_NOT_USED); LOG.debug(methodName + " ended"); return returnList; } // /** // * This method takes a list of {@link PurchasingApItem} objects and parses through them to see whether each item should be processed. If // * the item is valid to be processed this method will get it's accounts and add the accounts to a summary list. If one single account has // * the same account string variables as an account on another item then the two accounts total amounts will be summed and used as the total // * amount of the {@link SourceAccountingLine} object sent back in the list. // * // * See Also: {@link #getProcessablePurapItems(List, Set, Boolean, Boolean)} // * // * @param items - list of {@link PurchasingApItem} objects that need to be parsed // * @param itemTypeCodes - list of {@link org.kuali.module.purap.bo.ItemType} codes used in conjunction with itemTypeCodesAreIncluded parameter // * @param itemTypeCodesAreIncluded - value to tell whether the itemTypeCodes parameter lists inclusion or exclusion variables (see {@link #ITEM_TYPES_INCLUDED_VALUE}) // * @param useZeroTotals - value to tell whether to include zero dollar items (see {@link #ZERO_TOTALS_RETURNED_VALUE}) // * @return a list of {@link SourceAccountingLine} objects that represent a summing of all accounts across all derived processable items based on given criteria // */ // private Map<SourceAccountingLine, List<PurchasingApItem>> generateAccountSummaryWithItems(List<PurchasingApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals, // Boolean useAlternateAmount) { // Map<SourceAccountingLine, List<PurchasingApItem>>accountItemsMap = new HashMap(); // List<PurchasingApItem> itemsToProcess = getProcessablePurapItems(items, itemTypeCodes, itemTypeCodesAreIncluded, useZeroTotals); // Set<PurApAccountingLine> accountSet = new HashSet<PurApAccountingLine>(); // // for (PurchasingApItem currentItemFromDocument : items) { // if (PurApItemUtils.checkItemActive(currentItemFromDocument)) { // PurchasingApItem copyItemFromDocument = (PurchasingApItem)ObjectUtils.deepCopy(currentItemFromDocument); // for (PurApAccountingLine account : copyItemFromDocument.getSourceAccountingLines()) { // PurchasingApItem currentItem = (PurchasingApItem)ObjectUtils.deepCopy(copyItemFromDocument); // currentItem.setExtendedPriceForAccountSummary(account.getAmount()); // boolean thisAccountAlreadyInSet = false; // for (Iterator iter = accountSet.iterator(); iter.hasNext();) { // PurApAccountingLine alreadyAddedAccount = (PurApAccountingLine) iter.next(); // if (alreadyAddedAccount.accountStringsAreEqual(account)) { // if (useAlternateAmount) { // alreadyAddedAccount.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation().add(account.getAlternateAmountForGLEntryCreation())); // account.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation()); // } // else { // alreadyAddedAccount.setAmount(alreadyAddedAccount.getAmount().add(account.getAmount())); // account.setAmount(alreadyAddedAccount.getAmount()); // } // thisAccountAlreadyInSet = true; // break; // } // } // // PurApAccountingLine accountToAdd = (PurApAccountingLine) ObjectUtils.deepCopy(account); // SourceAccountingLine sourceLine = accountToAdd.generateSourceAccountingLine(); // if (!thisAccountAlreadyInSet) { // accountSet.add(accountToAdd); // if (accountToAdd.isEmpty()) { // String errorMessage = "Found an 'empty' account in summary generation " + accountToAdd.toString(); // LOG.error("generateAccountSummary() " + errorMessage); // throw new RuntimeException(errorMessage); // } // if (useAlternateAmount) { // sourceLine.setAmount(accountToAdd.getAlternateAmountForGLEntryCreation()); // } // List<PurchasingApItem> itemList = new ArrayList(); // itemList.add(currentItem); // accountItemsMap.put(sourceLine, itemList); // } // else { // for (Iterator mapIter = accountItemsMap.keySet().iterator(); mapIter.hasNext();) { // SourceAccountingLine accountFromMap = (SourceAccountingLine)mapIter.next(); // SourceAccountingLine tempAccount = (SourceAccountingLine)ObjectUtils.deepCopy(accountFromMap); // tempAccount.setAmount(sourceLine.getAmount()); // if (sourceLine.toString().equals(tempAccount.toString())) { // accountFromMap.setAmount(sourceLine.getAmount()); // List<PurchasingApItem> itemList = accountItemsMap.get(accountFromMap); // itemList.add(currentItem); // break; // } // } // } // } // } // } // // return accountItemsMap; // } private List<SourceAccountingLine> generateAccountSummary(List<PurApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals, Boolean useAlternateAmount) { List<PurApItem> itemsToProcess = getProcessablePurapItems(items, itemTypeCodes, itemTypeCodesAreIncluded, useZeroTotals); Set<PurApAccountingLine> accountSet = new HashSet<PurApAccountingLine>(); for (PurApItem currentItem : items) { if (PurApItemUtils.checkItemActive(currentItem)) { for (PurApAccountingLine account : currentItem.getSourceAccountingLines()) { boolean thisAccountAlreadyInSet = false; for (Iterator iter = accountSet.iterator(); iter.hasNext();) { PurApAccountingLine alreadyAddedAccount = (PurApAccountingLine) iter.next(); if (alreadyAddedAccount.accountStringsAreEqual(account)) { if (useAlternateAmount) { alreadyAddedAccount.setAlternateAmountForGLEntryCreation(alreadyAddedAccount.getAlternateAmountForGLEntryCreation().add(account.getAlternateAmountForGLEntryCreation())); } else { alreadyAddedAccount.setAmount(alreadyAddedAccount.getAmount().add(account.getAmount())); } thisAccountAlreadyInSet = true; break; } } if (!thisAccountAlreadyInSet) { PurApAccountingLine accountToAdd = (PurApAccountingLine) ObjectUtils.deepCopy(account); accountSet.add(accountToAdd); } } } } // convert list of PurApAccountingLine objects to SourceAccountingLineObjects List<SourceAccountingLine> sourceAccounts = new ArrayList<SourceAccountingLine>(); for (Iterator iter = accountSet.iterator(); iter.hasNext();) { PurApAccountingLine accountToAlter = (PurApAccountingLine) iter.next(); if (accountToAlter.isEmpty()) { String errorMessage = "Found an 'empty' account in summary generation " + accountToAlter.toString(); LOG.error("generateAccountSummary() " + errorMessage); throw new RuntimeException(errorMessage); } SourceAccountingLine sourceLine = accountToAlter.generateSourceAccountingLine(); if (useAlternateAmount) { sourceLine.setAmount(accountToAlter.getAlternateAmountForGLEntryCreation()); } sourceAccounts.add(sourceLine); } return sourceAccounts; } /** * This method takes a list of {@link PurchasingApItem} objects and parses through them to see if each one should be processed according * the the other variables passed in.<br> * <br> * Example 1:<br> * items = "ITEM", "SITM", "FRHT", "SPHD"<br> * itemTypeCodes = "FRHT"<br> * itemTypeCodesAreIncluded = ITEM_TYPES_EXCLUDED_VALUE<br> * return items "ITEM", "SITM", "FRHT", "SPHD"<br> * <br> * <br> * Example 2:<br> * items = "ITEM", "SITM", "FRHT", "SPHD"<br> * itemTypeCodes = "ITEM","FRHT"<br> * itemTypeCodesAreIncluded = ITEM_TYPES_INCLUDED_VALUE<br> * return items "ITEM", "FRHT"<br> * * @param items - list of {@link PurchasingApItem} objects that need to be parsed * @param itemTypeCodes - list of {@link org.kuali.module.purap.bo.ItemType} codes used in conjunction with itemTypeCodesAreIncluded parameter * @param itemTypeCodesAreIncluded - value to tell whether the itemTypeCodes parameter lists inclusion or exclusion variables (see {@link #ITEM_TYPES_INCLUDED_VALUE}) * @param useZeroTotals - value to tell whether to include zero dollar items (see {@link #ZERO_TOTALS_RETURNED_VALUE}) * @return a list of {@link PurchasingApItem} objects that should be used for processing by calling method */ private List<PurApItem> getProcessablePurapItems(List<PurApItem> items, Set itemTypeCodes, Boolean itemTypeCodesAreIncluded, Boolean useZeroTotals) { String methodName = "getProcessablePurapItems()"; List<PurApItem> newItemList = new ArrayList<PurApItem>(); // error out if we have an invalid 'itemTypeCodesAreIncluded' value if ( (!(ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded))) && (!(ITEM_TYPES_EXCLUDED_VALUE.equals(itemTypeCodesAreIncluded))) ) { throwRuntimeException(methodName, "Invalid parameter found while trying to find processable items for dealing with purchasing/accounts payable accounts"); } for (PurApItem currentItem : items) { if ( (itemTypeCodes != null) && (!(itemTypeCodes.isEmpty())) ) { // we have at least one entry in our item type code list boolean foundMatchInList = false; // check to see if this item type code is in the list for (Iterator iterator = itemTypeCodes.iterator(); iterator.hasNext();) { String itemTypeCode = (String) iterator.next(); // include this item if it's in the included list if (itemTypeCode.equals(currentItem.getItemType().getItemTypeCode())) { foundMatchInList = true; break; } } // check to see if item type code was found and if the list is describing included or excluded item types if ( (foundMatchInList) && (ITEM_TYPES_EXCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) ) { // this item type code is in the list // this item type code is excluded so we skip it continue; // skips current item } else if ( (!foundMatchInList) && (ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) ) { // this item type code is not in the list // this item type code is not included so we skip it continue; // skips current item } } else { // the item type code list is empty if (ITEM_TYPES_INCLUDED_VALUE.equals(itemTypeCodesAreIncluded)) { // the item type code list is empty and the list is supposed to contain the item types to include throwRuntimeException(methodName, "Invalid parameter and list of items found while trying to find processable items for dealing with purchasing/accounts payable accounts"); } } //TODO check to see if we should be allowing null in the extendedPrice (hjs) if ( (ZERO_TOTALS_NOT_RETURNED_VALUE.equals(useZeroTotals)) && (ObjectUtils.isNull(currentItem.getExtendedPrice()) || ((KualiDecimal.ZERO.compareTo(currentItem.getExtendedPrice())) == 0)) ) { // if we don't return zero dollar items then skip this one continue; } newItemList.add(currentItem); } return newItemList; } /** * * This method updates account amounts based on the percents. * @param document the document */ public void updateAccountAmounts(PurchasingAccountsPayableDocument document) { //TODO: Chris - this should probably be injected instead of using the locator (or put in doc) also don't forget to update the percent at fiscal approve //don't update if past the AP review level if((document instanceof PaymentRequestDocument) && SpringContext.getBean(PurapService.class).isFullDocumentEntryCompleted(document)){ return; } for (PurApItem item : document.getItems()) { updateItemAccountAmounts(item); } } /** * This method updates a single items account amounts * @param item */ public void updateItemAccountAmounts(PurApItem item) { if ( (item.getExtendedPrice()!=null) && KualiDecimal.ZERO.compareTo(item.getExtendedPrice()) != 0 ) { //TODO: is this the best sort to use? // Collections.sort( (List)item.getSourceAccountingLines() ); KualiDecimal accountTotal = KualiDecimal.ZERO; PurApAccountingLine lastAccount = null; for (PurApAccountingLine account : item.getSourceAccountingLines()) { BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString()).divide(new BigDecimal(100)); account.setAmount(new KualiDecimal(pct.multiply(new BigDecimal(item.getExtendedPrice().toString())))); accountTotal = accountTotal.add(account.getAmount()); lastAccount = account; } // put excess on last account if ( lastAccount != null ) { KualiDecimal difference = item.getExtendedPrice().subtract(accountTotal); lastAccount.setAmount(lastAccount.getAmount().add(difference)); } } else { //zero out if extended price is zero for (PurApAccountingLine account : item.getSourceAccountingLines()) { account.setAmount(KualiDecimal.ZERO); } } } public List<PurApAccountingLine> getAccountsFromItem(PurApItem item) { // TODO Auto-generated method stub return purApAccountingDao.getAccountingLinesForItem(item); } /** * Gets the purApAccountingDao attribute. * @return Returns the purApAccountingDao. */ public PurApAccountingDao getPurApAccountingDao() { return purApAccountingDao; } /** * Sets the purApAccountingDao attribute value. * @param purApAccountingDao The purApAccountingDao to set. */ public void setPurApAccountingDao(PurApAccountingDao purApAccountingDao) { this.purApAccountingDao = purApAccountingDao; } }
organize import
work/src/org/kuali/kfs/module/purap/service/impl/PurapAccountingServiceImpl.java
organize import
<ide><path>ork/src/org/kuali/kfs/module/purap/service/impl/PurapAccountingServiceImpl.java <ide> import org.kuali.module.purap.dao.PurApAccountingDao; <ide> import org.kuali.module.purap.document.PaymentRequestDocument; <ide> import org.kuali.module.purap.document.PurchasingAccountsPayableDocument; <del>import org.kuali.module.purap.document.PurchasingAccountsPayableDocumentBase; <ide> import org.kuali.module.purap.service.PurapAccountingService; <ide> import org.kuali.module.purap.service.PurapService; <ide> import org.kuali.module.purap.util.PurApItemUtils;
JavaScript
apache-2.0
0949225a61d31e6e867ec12444ebe253080b7336
0
ZmG/wsk_tutorial,ZmG/wsk_tutorial,ZmG/wsk_tutorial
// Generated by CoffeeScript 1.10.0 /* This is the main script file. It can attach to the terminal */ (function() { var COMPLETE_URL, EVENT_TYPES, adv_q, advancedTag, buildfunction, current_question, drawStatusMarker, endsWith, f, isNumber, j, leftside, len, logEvent, next, previous, progressIndicator, q, question, questionNumber, questions, results, staticDockerPs, statusMarker, switchToAdvanced, switchToBasic, tutorialTop; COMPLETE_URL = "/whats-next/"; /* Array of question objects */ staticDockerPs = "ID IMAGE COMMAND CREATED STATUS PORTS"; q = []; q.push({ html: "<h3>OpenWhisk Getting started</h3>\n<p>OpenWhisk is an event-driven compute platform that executes code in response to events or direct invocations.\n</p>\n<p>Examples of events include changes to database records, IoT sensor readings that exceed a certain temperature, new code commits to a GitHub repository, or simple HTTP requests from web or mobile apps. Events from external and internal event sources are channeled through a trigger, and rules allow actions to react to these events. </p>\n<p>Actions can be small snippets of Javascript or Swift code, or custom binaries embedded in a Docker container. Actions in OpenWhisk are instantly deployed and executed whenever a trigger fires. The more triggers fire, the more actions get invoked. If no trigger fires, no action code is running, so there is no cost.</p>\n<p>In addition to associating actions with triggers, it is possible to directly invoke an action by using the OpenWhisk API, CLI, or iOS SDK. A set of actions can also be chained without having to write any code. Each action in the chain is invoked in sequence with the output of one action passed as input to the next in the sequence.</p> <a href=\"https://new-console.ng.bluemix.net/docs/openwhisk/index.html\"> Getting Started with Bluemix OpenWhisk documentation</a>", assignment: "<h3>Assignment</h3>\n<p>Use a wsk command to see the full list of accepted arguments</p>\n<p>If you see a list of arguments then you know that you are all set with your wsk client installation.</p>", intermediateresults: [ function() { return "<p>Whisk argument swithces usually start with two dashes. Try \"--help\"</p>"; } ], tip: "<p>This emulator provides only a limited set of shell and wsk commands, so some commands may not work as expected</p>", command_expected: ['wsk', '--help'], result: "<p>Well done! Let's move to the next assignment.</p>" }); q.push({ html: "<h3>Creating a JavaScript Action</h3>\n<p>Actions encapsulate an actual code to be executed. One can think of an action as a piece of code that runs in response to an event. Actions support multiple language bindings including NodeJS, Swift and arbitrary binary programs encapsulated in Docker Containers. Actions invoke any part of an open ecosystem including existing Bluemix services for analytics, data, cognitive, or any other 3rd party service. </p>", assignment: "<h3>Assignment</h3>\n<p>Create an action called \"hello\" from the content of the \"hello.js\" file. \"hello.js\" had been already created.</p>", command_expected: ['wsk', 'action', 'create', 'hello', 'hello.js'], result: "<p>You found it! Way to go!</p>", tip: "For this assignment, the file 'hello.js' had been already created. Perform a 'ls' to ensure file exists and 'cat hello.js' to examine the contents of the file" }); q.push({ html: "<h3>List actions that have been created. </h3>\n<p>Existing and newly created actions can be looked up by using a wsk command.</p>", assignment: "<h3>Assignment</h3>\n<p>List the actions that were created</p>", command_expected: ['wsk', 'action', 'list'], result: "<p>Cool. Look at the result. You'll see that the action created in step 1 was listed</p>" }); q.push({ html: "<h3>Running an action using a blocking invocation</h3>\n<p>After you create your action, you can run it in the cloud in OpenWhisk with the 'invoke' command. You can invoke actions with a blocking\ninvocation or a non-blocking invocation by specifying a flag in the command. A blocking invocation waits until the action runs to completion and\nreturns a result. This example uses blocking invocation.</p>", assignment: "<h3>Assignment</h3>\n<p>Invoke the hello action utilizing blocking invocation. </p>", command_expected: ['wsk', 'action', 'invoke', '--blocking', 'hello'], command_show: ['wsk', 'action', 'invoke', '--blocking', 'hello'], result: "<p>Great! The command outputs two important pieces of information:\n<ul>\n <li>The activation ID (44794bd6aab74415b4e42a308d880e5b)</li>\n <li>The invocation result. The result in this case is the string Hello world \n returned by the JavaScript function. The activation ID can be used to \n retrieve the logs or result of the invocation at a future time.</li>\n</ul>", intermediateresults: [ function() { return "<p>You seem to be almost there. Did you feed in the \"wsk action\" command \"invoke --blocking hello\" parameters?"; } ], tip: "<ul>\n <li>Remember to use wsk action command.</li>\n</ul>" }); q.push({ html: "<h3>Running an action using a non-blocking invocation</h3>\n<p>If you don't need the action result right away, you can omit the --blocking flag to make a non-blocking invocation. You can get the result later by using the activation ID. </p>", assignment: "<h3>Assignment</h3>\n<p>Invoke the \"hello\" action utilizing non-blocking invocation. </p>", command_expected: ['wsk', 'action', 'invoke', 'hello'], command_show: ['wsk', 'action', 'invoke', 'hello'], result: "<p>Great! Action was invoked. Next we are going to obtain the result", intermediateresults: [ function() { return "<p>You seem to be almost there. Did you feed in the wsk action command \"invoke hello\" parameters"; } ], tip: "<ul>\n <li>Remember to use wsk action</li>\n</ul>" }); q.push({ html: "<h3>Get action's invocation result using the activation ID</h3>\n<p>You can get an actions result by using the action activation ID. If you forgot to record the activation ID, you can get a list of activations ordered from most recent to the oldest running the <code> wsk activation list</code> command </p>", assignment: "<h3>Assignment</h3>\n<p>Obtain a non-blocking action's result. Remember, a non-blocking invocation may execute in the background so obtaining the result requires the activation ID</p>", command_expected: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], command_show: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], result: "<p>Great! You Have completed the Basic wsk CLI tutorial! Hit next to move on to the <em style=\"color:crimson;\">Advanced</em> tutorial!", tip: "<ul>\n <li>You need to use the <code> wsk activation result</code> command along with the activation ID</li>\n</ul>", intermediateresults: [ function() { var data; $('#instructions .assignment').hide(); $('#tips, #command').hide(); $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the basic wsk commands!</p>\n <p><strong>Did you enjoy this tutorial? </p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n <p> - Or - </p>\n <p>Continue to learn the advanced features of the wsk CLI. </p><p><a onclick=\"switchToAdvanced()\" class='btn btn-primary secondary-action-button'>Start <em style=\"color:crimson;\">Advanced</em> tutorial</a></p>\n\n</div>"); data = { type: EVENT_TYPES.complete }; return logEvent(data); } ], finishedCallback: function() { webterm.clear(); return webterm.echo(myTerminal()); } }); /* Array of ADVANCED question objects */ adv_q = []; adv_q.push({ html: "<h3>Creating Sequence of actions</h3>\n<p>You can create an action that chains together a sequence of actions.Several utility actions are provided in a package called /whisk.system/util that you can use to create your first sequence. You can learn more about packages in the Packages section. </p>", assignment: "<h3>Assignment</h3>\n<p>1. Display the actions in the /whisk.system/util package using <code>wsk package get --summary /whisk.system/util</code> 2. Create an action sequence called \"sequenceOfActions\" so that the result of the <code>/whisk.system/util/cat</code> action is passed as an argument to the <code>/whisk.system/util/sort</code> action. </p>", command_expected: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], command_show: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], result: "<p>Great! You Have completed the Advanced CLI tutorial!", tip: "<ul>\n <li>Creating action sequences is similar to creating a single action except one needs to add the \"--sequence\" switch and specify a list of comma separated existing actions</li>\n</ul>", intermediateresults: [ function() { var data; $('#instructions .assignment').hide(); $('#tips, #command').hide(); $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the <em style=\"color:aquamarine;\">Advanced</em> wsk commands!</p>\n <p><strong>Did you enjoy this tutorial?</p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n <p> - Or - </p>\n <p>Return back to getting started. </p><p><a onclick=\"leaveFullSizeMode()\" class='btn btn-primary secondary-action-button'>Return to Getting Started</a></p>\n</div>"); data = { type: EVENT_TYPES.complete }; return logEvent(data); } ], finishedCallback: function() { webterm.clear(); return webterm.echo(myTerminal()); } }); questions = []; /* Register the terminal */ this.webterm = $('#terminal').terminal(interpreter, basesettings); EVENT_TYPES = { none: "none", start: "start", command: "command", next: "next", peek: "peek", feedback: "feedback", complete: "complete" }; /* Sending events to the server (disabled for ice tutorial) */ logEvent = function(data, feedback) { return console.log(data); }; /* Event handlers */ $('#buttonNext').click(function(e) { this.setAttribute('disabled', 'disabled'); console.log(e); return next(); }); $('#buttonFinish').click(function() { return window.open(COMPLETE_URL); }); $('#buttonPrevious').click(function() { previous(); return $('#results').hide(); }); $('#leftside').bind('mousewheel', function(event, delta, deltaX, deltaY) { this.scrollTop += deltaY * -30; return event.preventDefault(); }); $('#feedbackSubmit').click(function() { var data, feedback; feedback = $('#feedbackInput').val(); data = { type: EVENT_TYPES.feedback, feedback: feedback }; return logEvent(data, feedback = true); }); $('#fullSizeOpen').click(function() { return goFullScreen(); }); isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; this.goFullScreen = function(start) { var index; window.scrollTo(0, 0); console.debug("going to fullsize mode"); $('.togglesize').removeClass('startsize').addClass('fullsize'); $('.hide-when-small').css({ display: 'inherit' }); $('.hide-when-full').css({ display: 'none' }); if (start === 'adv') { switchToAdvanced(); } else if (start === 'basic') { switchToBasic(); } else if (isNumber(start)) { next(start); } else if (endsWith(start, 'ADV')) { switchToAdvanced(); index = start.split('-')[0]; next(index); } else { next(0); } webterm.resize(); return setTimeout(function() { return logEvent({ type: EVENT_TYPES.start }); }, 3000); }; $('#fullSizeClose').click(function() { return leaveFullSizeMode(); }); this.leaveFullSizeMode = function() { console.debug("leaving full-size mode"); $('.togglesize').removeClass('fullsize').addClass('startsize'); $('.hide-when-small').css({ display: 'none' }); $('.hide-when-full').css({ display: 'inherit' }); return webterm.resize(); }; $('#command').click(function() { var data; if (!$('#commandHiddenText').hasClass('hidden')) { $('#commandHiddenText').addClass("hidden").hide(); $('#commandShownText').hide().removeClass("hidden").fadeIn(); } data = { type: EVENT_TYPES.peek }; return logEvent(data); }); /* Navigation amongst the questions */ endsWith = function(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }; current_question = 0; window.next = next = function(which) { var data; $('#marker-' + current_question).addClass("complete").removeClass("active"); if (which === 'ADV') { switchToAdvanced(); } else if (which === '←') { switchToBasic(); } else if (!which && which !== 0) { current_question++; if (current_question === questions.length) { next('ADV'); } } else { current_question = which; } questions[current_question](); results.clear(); this.webterm.focus(); if (!$('#commandShownText').hasClass('hidden')) { $('#commandShownText').addClass("hidden"); $('#commandHiddenText').removeClass("hidden").show(); } if (window.advancedTut === true) { history.pushState({}, "", "#" + current_question + "-ADV"); window.location.hash = "#" + current_question + "-ADV"; } else { history.pushState({}, "", "#" + current_question); window.location.hash = "#" + current_question; } data = { 'type': EVENT_TYPES.next }; logEvent(data); $('#marker-' + current_question).removeClass("complete").addClass("active"); $('#question-number').find('text').get(0).textContent = current_question; $('#instructions .assignment').show(); $('#tips, #command').show(); }; previous = function() { current_question--; questions[current_question](); results.clear(); this.webterm.focus(); }; results = { set: function(htmlText, intermediate) { if (intermediate) { console.debug("intermediate text received"); $('#results').addClass('intermediate'); $('#buttonNext').hide(); } else { $('#buttonNext').show(); } return window.setTimeout((function() { $('#resulttext').html(htmlText); $('#results').fadeIn(); return $('#buttonNext').removeAttr('disabled'); }), 300); }, clear: function() { $('#resulttext').html(""); return $('#results').fadeOut('slow'); } }; /* Transform question objects into functions */ buildfunction = function(question) { var _q; _q = question; return function() { console.debug("function called"); $('#instructions').hide().fadeIn(); $('#instructions .text').html(_q.html); $('#instructions .assignment').html(_q.assignment); $('#tipShownText').html(_q.tip); if (_q.command_show) { $('#commandShownText').html(_q.command_show.join(' ')); } else { $('#commandShownText').html(_q.command_expected.join(' ')); } if (_q.currentDockerPs != null) { window.currentDockerPs = _q.currentDockerPs; } else { window.currentDockerPs = staticDockerPs; } if (_q.currentLocalImages != null) { window.currentLocalImages = _q.currentLocalImages; } if (_q.currentCloudImages != null) { window.currentCloudImages = _q.currentCloudImages; } if (_q.currentCloudImages != null) { window.currentCloudImages = _q.currentCloudImages; } if (_q.currentIceGroups != null) { window.currentIceGroups = _q.currentIceGroups; } if (_q.currentIcePs != null) { window.currentIcePs = _q.currentIcePs; } else { window.finishedCallback = function() { return ""; }; } window.immediateCallback = function(input, stop) { var data, doNotExecute; if (stop === true) { doNotExecute = true; } else { doNotExecute = false; } if (doNotExecute !== true) { console.log(input); data = { 'type': EVENT_TYPES.command, 'command': input.join(' '), 'result': 'fail' }; if (input.containsAllOfTheseParts(_q.command_expected)) { data.result = 'success'; setTimeout((function() { this.webterm.disable(); return $('#buttonNext').focus(); }), 1000); results.set(_q.result); console.debug("contains match"); } else { console.debug("wrong command received"); } logEvent(data); } }; window.intermediateResults = function(input) { var intermediate; if (_q.intermediateresults) { return results.set(_q.intermediateresults[input](), intermediate = true); } }; }; }; statusMarker = $('#progress-marker-0'); progressIndicator = $('#progress-indicator'); leftside = $('#leftside'); tutorialTop = $('#tutorialTop'); advancedTag = $('#advancedTag'); window.switchToBasic = switchToBasic = function() { var f, j, len, question, questionNumber; window.advancedTut = false; questions = []; statusMarker.prevAll('span').remove(); statusMarker.nextAll('span').remove(); leftside.animate({ backgroundColor: "#26343f" }, 1000); tutorialTop.animate({ backgroundColor: "rgb(59, 74, 84)" }, 1000); advancedTag.fadeOut(); questionNumber = 0; for (j = 0, len = q.length; j < len; j++) { question = q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); if (questionNumber > 0) { $('#marker-' + questionNumber).removeClass("active").removeClass("complete"); } else { $('#marker-' + questionNumber).removeClass("complete").addClass("active"); } questionNumber++; } drawStatusMarker('ADV'); return next(0); }; window.switchToAdvanced = switchToAdvanced = function() { var f, j, len, marker, question, questionNumber; questions = []; window.advancedTut = true; statusMarker.prevAll('span').remove(); statusMarker.nextAll('span').remove(); leftside.animate({ backgroundColor: "#543B3B" }, 1000); tutorialTop.animate({ backgroundColor: "#3F2626" }, 1000); advancedTag.fadeIn(); marker = statusMarker.clone(); marker.prependTo(progressIndicator); marker.title = 'Go back to the Basic Tutorial'; marker.attr("id", "marker-" + 'BSC'); marker.find('text').get(0).textContent = '←'; marker.click(function() { return switchToBasic(); }); marker.removeClass("active"); questionNumber = 0; for (j = 0, len = adv_q.length; j < len; j++) { question = adv_q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); if (questionNumber > 0) { $('#marker-' + questionNumber).removeClass("active").removeClass("complete"); } else { $('#marker-' + questionNumber).removeClass("complete").addClass("active"); } questionNumber++; } return next(0); }; drawStatusMarker = function(i) { var marker; if (i === 0) { marker = statusMarker; } else { marker = statusMarker.clone(); marker.appendTo(progressIndicator); } marker.attr("id", "marker-" + i); marker.find('text').get(0).textContent = i; return marker.click(function() { return next(i); }); }; questionNumber = 0; for (j = 0, len = q.length; j < len; j++) { question = q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); questionNumber++; } drawStatusMarker('ADV'); /* Initialization of program */ /*if (window.location.hash) try currentquestion = window.location.hash.split('#')[1].toNumber() * questions[currentquestion]() * current_question = currentquestion next(currentquestion) catch err questions[0]() else questions[0]() */ $('#results').hide(); }).call(this);
wsk_tutorial/static/js/steps.js
// Generated by CoffeeScript 1.10.0 /* This is the main script file. It can attach to the terminal */ (function() { var COMPLETE_URL, EVENT_TYPES, adv_q, advancedTag, buildfunction, current_question, drawStatusMarker, endsWith, f, isNumber, j, leftside, len, logEvent, next, previous, progressIndicator, q, question, questionNumber, questions, results, staticDockerPs, statusMarker, switchToAdvanced, switchToBasic, tutorialTop; COMPLETE_URL = "/whats-next/"; /* Array of question objects */ staticDockerPs = "ID IMAGE COMMAND CREATED STATUS PORTS"; q = []; q.push({ html: "<h3>OpenWhisk Getting started</h3>\n<p>OpenWhisk is an event-driven compute platform that executes code in response to events or direct invocations.\n</p>\n<p>Examples of events include changes to database records, IoT sensor readings that exceed a certain temperature, new code commits to a GitHub repository, or simple HTTP requests from web or mobile apps. Events from external and internal event sources are channeled through a trigger, and rules allow actions to react to these events. </p>\n<p>Actions can be small snippets of Javascript or Swift code, or custom binaries embedded in a Docker container. Actions in OpenWhisk are instantly deployed and executed whenever a trigger fires. The more triggers fire, the more actions get invoked. If no trigger fires, no action code is running, so there is no cost.</p>\n<p>In addition to associating actions with triggers, it is possible to directly invoke an action by using the OpenWhisk API, CLI, or iOS SDK. A set of actions can also be chained without having to write any code. Each action in the chain is invoked in sequence with the output of one action passed as input to the next in the sequence.</p> <a href=\"https://new-console.ng.bluemix.net/docs/openwhisk/index.html\"> Getting Started with Bluemix OpenWhisk documentation</a>", assignment: "<h3>Assignment</h3>\n<p>Use a wsk command to see the full list of accepted arguments</p>\n<p>If you see a list of arguments then you know that you are all set with your wsk client installation.</p>", intermediateresults: [ function() { return "<p>Whisk argument swithces usually start with two dashes. Try \"--help\"</p>"; } ], tip: "<p>This emulator provides only a limited set of shell and wsk commands, so some commands may not work as expected</p>", command_expected: ['wsk', '--help'], result: "<p>Well done! Let's move to the next assignment.</p>" }); q.push({ html: "<h3>Creating a JavaScript Action</h3>\n<p>Actions encapsulate an actual code to be executed. One can think of an action as a piece of code that runs in response to an event. Actions support multiple language bindings including NodeJS, Swift and arbitrary binary programs encapsulated in Docker Containers. Actions invoke any part of an open ecosystem including existing Bluemix services for analytics, data, cognitive, or any other 3rd party service. </p>", assignment: "<h3>Assignment</h3>\n<p>Create an action called \"hello\" from the content of the \"hello.js\" file. \"hello.js\" had been already created.</p>", command_expected: ['wsk', 'action', 'create', 'hello', 'hello.js'], result: "<p>You found it! Way to go!</p>", tip: "For this assignment, the file 'hello.js' had been already created. Perform a 'ls' to ensure file exists and 'cat hello.js' to examine the contents of the file" }); q.push({ html: "<h3>List actions that have been created. </h3>\n<p>Existing and newly created actions can be looked up by using a wsk command.</p>", assignment: "<h3>Assignment</h3>\n<p>List the actions that were created</p>", command_expected: ['wsk', 'action', 'list'], result: "<p>Cool. Look at the result. You'll see that the action created in step 1 was listed</p>" }); q.push({ html: "<h3>Running an action using a blocking invocation</h3>\n<p>After you create your action, you can run it in the cloud in OpenWhisk with the 'invoke' command. You can invoke actions with a blocking\ninvocation or a non-blocking invocation by specifying a flag in the command. A blocking invocation waits until the action runs to completion and\nreturns a result. This example uses blocking invocation.</p>", assignment: "<h3>Assignment</h3>\n<p>Invoke the hello action utilizing blocking invocation. </p>", command_expected: ['wsk', 'action', 'invoke', '--blocking', 'hello'], command_show: ['wsk', 'action', 'invoke', '--blocking', 'hello'], result: "<p>Great! The command outputs two important pieces of information:\n<ul>\n <li>The activation ID (44794bd6aab74415b4e42a308d880e5b)</li>\n <li>The invocation result. The result in this case is the string Hello world \n returned by the JavaScript function. The activation ID can be used to \n retrieve the logs or result of the invocation at a future time.</li>\n</ul>", intermediateresults: [ function() { return "<p>You seem to be almost there. Did you feed in the \"wsk action\" command \"invoke --blocking hello\" parameters?"; } ], tip: "<ul>\n <li>Remember to use wsk action command.</li>\n</ul>" }); q.push({ html: "<h3>Running an action using a non-blocking invocation</h3>\n<p>If you don't need the action result right away, you can omit the --blocking flag to make a non-blocking invocation. You can get the result later by using the activation ID. </p>", assignment: "<h3>Assignment</h3>\n<p>Invoke the \"hello\" action utilizing non-blocking invocation. </p>", command_expected: ['wsk', 'action', 'invoke', 'hello'], command_show: ['wsk', 'action', 'invoke', 'hello'], result: "<p>Great! Action was invoked. Next we are going to obtain the result", intermediateresults: [ function() { return "<p>You seem to be almost there. Did you feed in the wsk action command \"invoke hello\" parameters"; } ], tip: "<ul>\n <li>Remember to use wsk action</li>\n</ul>" }); q.push({ html: "<h3>Get action's invocation result using the activation ID</h3>\n<p>You can get an actions result by using the action activation ID. If you forgot to record the activation ID, you can get a list of activations ordered from most recent to the oldest running the <code> wsk activation list</code> command </p>", assignment: "<h3>Assignment</h3>\n<p>Obtain a non-blocking action's result. Remember, a non-blocking invocation may execute in the background so obtaining the result requires the activation ID</p>", command_expected: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], command_show: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], result: "<p>Great! You Have completed the ice CLI tutorial! Hit next to move on to the <em style=\"color:crimson;\">Advanced</em> tutorial!", tip: "<ul>\n <li>You need to use the <code> wsk activation result</code> command along with the activation ID</li>\n</ul>", intermediateresults: [ function() { var data; $('#instructions .assignment').hide(); $('#tips, #command').hide(); $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the basic wsk commands!</p>\n <p><strong>Did you enjoy this tutorial? </p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n <p> - Or - </p>\n <p>Continue to learn the advanced features of the wsk CLI. </p><p><a onclick=\"switchToAdvanced()\" class='btn btn-primary secondary-action-button'>Start <em style=\"color:crimson;\">Advanced</em> tutorial</a></p>\n\n</div>"); data = { type: EVENT_TYPES.complete }; return logEvent(data); } ], finishedCallback: function() { webterm.clear(); return webterm.echo(myTerminal()); } }); /* Array of ADVANCED question objects */ adv_q = []; adv_q.push({ html: "<h3>Creating Sequence of actions</h3>\n<p>You can create an action that chains together a sequence of actions.Several utility actions are provided in a package called /whisk.system/util that you can use to create your first sequence. You can learn more about packages in the Packages section. </p>", assignment: "<h3>Assignment</h3>\n<p>1. Display the actions in the /whisk.system/util package using <code>wsk package get --summary /whisk.system/util</code> 2. Create an action sequence called \"sequenceOfActions\" so that the result of the <code>/whisk.system/util/cat</code> action is passed as an argument to the <code>/whisk.system/util/sort</code> action. </p>", command_expected: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], command_show: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], result: "<p>Great! ", tip: "<ul>\n <li>Creating action sequences is similar to creating a single action except one needs to add the \"--sequence\" switch and specify a list of comma separated existing actions</li>\n</ul>", intermediateresults: [ function() { var data; $('#instructions .assignment').hide(); $('#tips, #command').hide(); $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the <em style=\"color:aquamarine;\">Advanced</em> wsk commands!</p>\n <p><strong>Did you enjoy this tutorial?</p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n</div>"); data = { type: EVENT_TYPES.complete }; return logEvent(data); } ], finishedCallback: function() { webterm.clear(); return webterm.echo(myTerminal()); } }); questions = []; /* Register the terminal */ this.webterm = $('#terminal').terminal(interpreter, basesettings); EVENT_TYPES = { none: "none", start: "start", command: "command", next: "next", peek: "peek", feedback: "feedback", complete: "complete" }; /* Sending events to the server (disabled for ice tutorial) */ logEvent = function(data, feedback) { return console.log(data); }; /* Event handlers */ $('#buttonNext').click(function(e) { this.setAttribute('disabled', 'disabled'); console.log(e); return next(); }); $('#buttonFinish').click(function() { return window.open(COMPLETE_URL); }); $('#buttonPrevious').click(function() { previous(); return $('#results').hide(); }); $('#leftside').bind('mousewheel', function(event, delta, deltaX, deltaY) { this.scrollTop += deltaY * -30; return event.preventDefault(); }); $('#feedbackSubmit').click(function() { var data, feedback; feedback = $('#feedbackInput').val(); data = { type: EVENT_TYPES.feedback, feedback: feedback }; return logEvent(data, feedback = true); }); $('#fullSizeOpen').click(function() { return goFullScreen(); }); isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; this.goFullScreen = function(start) { var index; window.scrollTo(0, 0); console.debug("going to fullsize mode"); $('.togglesize').removeClass('startsize').addClass('fullsize'); $('.hide-when-small').css({ display: 'inherit' }); $('.hide-when-full').css({ display: 'none' }); if (start === 'adv') { switchToAdvanced(); } else if (start === 'basic') { switchToBasic(); } else if (isNumber(start)) { next(start); } else if (endsWith(start, 'ADV')) { switchToAdvanced(); index = start.split('-')[0]; next(index); } else { next(0); } webterm.resize(); return setTimeout(function() { return logEvent({ type: EVENT_TYPES.start }); }, 3000); }; $('#fullSizeClose').click(function() { return leaveFullSizeMode(); }); this.leaveFullSizeMode = function() { console.debug("leaving full-size mode"); $('.togglesize').removeClass('fullsize').addClass('startsize'); $('.hide-when-small').css({ display: 'none' }); $('.hide-when-full').css({ display: 'inherit' }); return webterm.resize(); }; $('#command').click(function() { var data; if (!$('#commandHiddenText').hasClass('hidden')) { $('#commandHiddenText').addClass("hidden").hide(); $('#commandShownText').hide().removeClass("hidden").fadeIn(); } data = { type: EVENT_TYPES.peek }; return logEvent(data); }); /* Navigation amongst the questions */ endsWith = function(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; }; current_question = 0; window.next = next = function(which) { var data; $('#marker-' + current_question).addClass("complete").removeClass("active"); if (which === 'ADV') { switchToAdvanced(); } else if (which === '←') { switchToBasic(); } else if (!which && which !== 0) { current_question++; if (current_question === questions.length) { next('ADV'); } } else { current_question = which; } questions[current_question](); results.clear(); this.webterm.focus(); if (!$('#commandShownText').hasClass('hidden')) { $('#commandShownText').addClass("hidden"); $('#commandHiddenText').removeClass("hidden").show(); } if (window.advancedTut === true) { history.pushState({}, "", "#" + current_question + "-ADV"); window.location.hash = "#" + current_question + "-ADV"; } else { history.pushState({}, "", "#" + current_question); window.location.hash = "#" + current_question; } data = { 'type': EVENT_TYPES.next }; logEvent(data); $('#marker-' + current_question).removeClass("complete").addClass("active"); $('#question-number').find('text').get(0).textContent = current_question; $('#instructions .assignment').show(); $('#tips, #command').show(); }; previous = function() { current_question--; questions[current_question](); results.clear(); this.webterm.focus(); }; results = { set: function(htmlText, intermediate) { if (intermediate) { console.debug("intermediate text received"); $('#results').addClass('intermediate'); $('#buttonNext').hide(); } else { $('#buttonNext').show(); } return window.setTimeout((function() { $('#resulttext').html(htmlText); $('#results').fadeIn(); return $('#buttonNext').removeAttr('disabled'); }), 300); }, clear: function() { $('#resulttext').html(""); return $('#results').fadeOut('slow'); } }; /* Transform question objects into functions */ buildfunction = function(question) { var _q; _q = question; return function() { console.debug("function called"); $('#instructions').hide().fadeIn(); $('#instructions .text').html(_q.html); $('#instructions .assignment').html(_q.assignment); $('#tipShownText').html(_q.tip); if (_q.command_show) { $('#commandShownText').html(_q.command_show.join(' ')); } else { $('#commandShownText').html(_q.command_expected.join(' ')); } if (_q.currentDockerPs != null) { window.currentDockerPs = _q.currentDockerPs; } else { window.currentDockerPs = staticDockerPs; } if (_q.currentLocalImages != null) { window.currentLocalImages = _q.currentLocalImages; } if (_q.currentCloudImages != null) { window.currentCloudImages = _q.currentCloudImages; } if (_q.currentCloudImages != null) { window.currentCloudImages = _q.currentCloudImages; } if (_q.currentIceGroups != null) { window.currentIceGroups = _q.currentIceGroups; } if (_q.currentIcePs != null) { window.currentIcePs = _q.currentIcePs; } else { window.finishedCallback = function() { return ""; }; } window.immediateCallback = function(input, stop) { var data, doNotExecute; if (stop === true) { doNotExecute = true; } else { doNotExecute = false; } if (doNotExecute !== true) { console.log(input); data = { 'type': EVENT_TYPES.command, 'command': input.join(' '), 'result': 'fail' }; if (input.containsAllOfTheseParts(_q.command_expected)) { data.result = 'success'; setTimeout((function() { this.webterm.disable(); return $('#buttonNext').focus(); }), 1000); results.set(_q.result); console.debug("contains match"); } else { console.debug("wrong command received"); } logEvent(data); } }; window.intermediateResults = function(input) { var intermediate; if (_q.intermediateresults) { return results.set(_q.intermediateresults[input](), intermediate = true); } }; }; }; statusMarker = $('#progress-marker-0'); progressIndicator = $('#progress-indicator'); leftside = $('#leftside'); tutorialTop = $('#tutorialTop'); advancedTag = $('#advancedTag'); window.switchToBasic = switchToBasic = function() { var f, j, len, question, questionNumber; window.advancedTut = false; questions = []; statusMarker.prevAll('span').remove(); statusMarker.nextAll('span').remove(); leftside.animate({ backgroundColor: "#26343f" }, 1000); tutorialTop.animate({ backgroundColor: "rgb(59, 74, 84)" }, 1000); advancedTag.fadeOut(); questionNumber = 0; for (j = 0, len = q.length; j < len; j++) { question = q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); if (questionNumber > 0) { $('#marker-' + questionNumber).removeClass("active").removeClass("complete"); } else { $('#marker-' + questionNumber).removeClass("complete").addClass("active"); } questionNumber++; } drawStatusMarker('ADV'); return next(0); }; window.switchToAdvanced = switchToAdvanced = function() { var f, j, len, marker, question, questionNumber; questions = []; window.advancedTut = true; statusMarker.prevAll('span').remove(); statusMarker.nextAll('span').remove(); leftside.animate({ backgroundColor: "#543B3B" }, 1000); tutorialTop.animate({ backgroundColor: "#3F2626" }, 1000); advancedTag.fadeIn(); marker = statusMarker.clone(); marker.prependTo(progressIndicator); marker.title = 'Go back to the Basic Tutorial'; marker.attr("id", "marker-" + 'BSC'); marker.find('text').get(0).textContent = '←'; marker.click(function() { return switchToBasic(); }); marker.removeClass("active"); questionNumber = 0; for (j = 0, len = adv_q.length; j < len; j++) { question = adv_q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); if (questionNumber > 0) { $('#marker-' + questionNumber).removeClass("active").removeClass("complete"); } else { $('#marker-' + questionNumber).removeClass("complete").addClass("active"); } questionNumber++; } return next(0); }; drawStatusMarker = function(i) { var marker; if (i === 0) { marker = statusMarker; } else { marker = statusMarker.clone(); marker.appendTo(progressIndicator); } marker.attr("id", "marker-" + i); marker.find('text').get(0).textContent = i; return marker.click(function() { return next(i); }); }; questionNumber = 0; for (j = 0, len = q.length; j < len; j++) { question = q[j]; f = buildfunction(question); questions.push(f); drawStatusMarker(questionNumber); questionNumber++; } drawStatusMarker('ADV'); /* Initialization of program */ /*if (window.location.hash) try currentquestion = window.location.hash.split('#')[1].toNumber() * questions[currentquestion]() * current_question = currentquestion next(currentquestion) catch err questions[0]() else questions[0]() */ $('#results').hide(); }).call(this);
0.1.5
wsk_tutorial/static/js/steps.js
0.1.5
<ide><path>sk_tutorial/static/js/steps.js <ide> assignment: "<h3>Assignment</h3>\n<p>Obtain a non-blocking action's result. Remember, a non-blocking invocation may execute in the background so obtaining the result requires the activation ID</p>", <ide> command_expected: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], <ide> command_show: ["wsk", "activation", "result", "6bf1f670ee614a7eb5af3c9fde813043"], <del> result: "<p>Great! You Have completed the ice CLI tutorial! Hit next to move on to the <em style=\"color:crimson;\">Advanced</em> tutorial!", <add> result: "<p>Great! You Have completed the Basic wsk CLI tutorial! Hit next to move on to the <em style=\"color:crimson;\">Advanced</em> tutorial!", <ide> tip: "<ul>\n <li>You need to use the <code> wsk activation result</code> command along with the activation ID</li>\n</ul>", <ide> intermediateresults: [ <ide> function() { <ide> assignment: "<h3>Assignment</h3>\n<p>1. Display the actions in the /whisk.system/util package using <code>wsk package get --summary /whisk.system/util</code> 2. Create an action sequence called \"sequenceOfActions\" so that the result of the <code>/whisk.system/util/cat</code> action is passed as an argument to the <code>/whisk.system/util/sort</code> action. </p>", <ide> command_expected: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], <ide> command_show: ["wsk", "action", "create", "sequenceOfActions", "--sequence", "/whisk.system/util/cat,/whisk.system/util/sort"], <del> result: "<p>Great! ", <add> result: "<p>Great! You Have completed the Advanced CLI tutorial!", <ide> tip: "<ul>\n <li>Creating action sequences is similar to creating a single action except one needs to add the \"--sequence\" switch and specify a list of comma separated existing actions</li>\n</ul>", <ide> intermediateresults: [ <ide> function() { <ide> var data; <ide> $('#instructions .assignment').hide(); <ide> $('#tips, #command').hide(); <del> $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the <em style=\"color:aquamarine;\">Advanced</em> wsk commands!</p>\n <p><strong>Did you enjoy this tutorial?</p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n</div>"); <add> $('#instructions .text').html("<div class=\"complete\">\n <h3>Congratulations!</h3>\n <p>You have mastered the <em style=\"color:aquamarine;\">Advanced</em> wsk commands!</p>\n <p><strong>Did you enjoy this tutorial?</p>\n <h3>Your next steps</h3>\n <ol>\n <li><a href=\"#\" onClick=\"leaveFullSizeMode()\">Close</a> this tutorial, and continue with the rest of the getting started.</li>\n </ol>\n <p> - Or - </p>\n <p>Return back to getting started. </p><p><a onclick=\"leaveFullSizeMode()\" class='btn btn-primary secondary-action-button'>Return to Getting Started</a></p>\n</div>"); <ide> data = { <ide> type: EVENT_TYPES.complete <ide> };
Java
apache-2.0
b15578a5fe4d9b036cb567a2e329eb4ad2caf59c
0
GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch,GlenRSmith/elasticsearch
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ilm; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.routing.UnassignedInfo.Reason; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.node.Node; import org.elasticsearch.xpack.core.ilm.ClusterStateWaitStep.Result; import org.elasticsearch.xpack.core.ilm.Step.StepKey; import java.util.Collections; import java.util.Map; import static org.elasticsearch.xpack.core.ilm.step.info.AllocationInfo.allShardsActiveAllocationInfo; import static org.elasticsearch.xpack.core.ilm.step.info.AllocationInfo.waitingForActiveShardsAllocationInfo; public class AllocationRoutedStepTests extends AbstractStepTestCase<AllocationRoutedStep> { @Override public AllocationRoutedStep createRandomInstance() { StepKey stepKey = randomStepKey(); StepKey nextStepKey = randomStepKey(); return new AllocationRoutedStep(stepKey, nextStepKey); } @Override public AllocationRoutedStep mutateInstance(AllocationRoutedStep instance) { StepKey key = instance.getKey(); StepKey nextKey = instance.getNextStepKey(); switch (between(0, 1)) { case 0: key = new StepKey(key.getPhase(), key.getAction(), key.getName() + randomAlphaOfLength(5)); break; case 1: nextKey = new StepKey(key.getPhase(), key.getAction(), key.getName() + randomAlphaOfLength(5)); break; default: throw new AssertionError("Illegal randomisation branch"); } return new AllocationRoutedStep(key, nextKey); } @Override public AllocationRoutedStep copyInstance(AllocationRoutedStep instance) { return new AllocationRoutedStep(instance.getKey(), instance.getNextStepKey()); } public void testConditionMet() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> requires = AllocateActionTests.randomAllocationRoutingMap(1, 5); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(true, null)); } public void testRequireConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> requires = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testClusterExcludeFiltersConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); IndexMetadata indexMetadata = IndexMetadata.builder(index.getName()).settings(existingSettings).numberOfShards(1) .numberOfReplicas(1).build(); ImmutableOpenMap.Builder<String, IndexMetadata> indices = ImmutableOpenMap.<String, IndexMetadata>builder().fPut(index.getName(), indexMetadata); Settings clusterSettings = Settings.builder() .put("cluster.routing.allocation.exclude._id", "node1") .build(); Settings.Builder nodeSettingsBuilder = Settings.builder(); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE) .metadata(Metadata.builder().indices(indices.build()).transientSettings(clusterSettings)) .nodes(DiscoveryNodes.builder() .add(DiscoveryNode.createLocal(nodeSettingsBuilder.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9200), "node1")) .add(DiscoveryNode.createLocal(nodeSettingsBuilder.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9201), "node2"))) .routingTable(RoutingTable.builder().add(indexRoutingTable).build()).build(); Result actualResult = step.isConditionMet(index, clusterState); Result expectedResult = new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(1, 1)); assertEquals(expectedResult.isComplete(), actualResult.isComplete()); assertEquals(expectedResult.getInfomationContext(), actualResult.getInfomationContext()); } public void testExcludeConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> excludes = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testIncludeConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testConditionNotMetDueToRelocation() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> requires = AllocateActionTests.randomAllocationRoutingMap(1, 5); Settings.Builder existingSettings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_PREFIX + "._id", "node1") .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); ShardRouting shardOnNode1 = TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED); shardOnNode1 = shardOnNode1.relocate("node3", 230); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(shardOnNode1) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 2))); } public void testExecuteAllocateNotComplete() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 1), "node2", true, ShardRoutingState.STARTED)); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testExecuteAllocateNotCompleteOnlyOneCopyAllocated() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testExecuteAllocateUnassigned() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 1), null, null, true, ShardRoutingState.UNASSIGNED, TestShardRouting.randomUnassignedInfo("the shard is intentionally unassigned"))); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, waitingForActiveShardsAllocationInfo(0))); } /** * this tests the scenario where * * PUT index * { * "settings": { * "number_of_replicas": 0, * "number_of_shards": 1 * } * } * * PUT index/_settings * { * "number_of_replicas": 1, * "index.routing.allocation.include._name": "{node-name}" * } */ public void testExecuteReplicasNotAllocatedOnSingleNode() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), null, null, false, ShardRoutingState.UNASSIGNED, new UnassignedInfo(Reason.REPLICA_ADDED, "no attempt"))); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 1, 1, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, waitingForActiveShardsAllocationInfo(1))); } public void testExecuteIndexMissing() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE).build(); AllocationRoutedStep step = createRandomInstance(); Result actualResult = step.isConditionMet(index, clusterState); assertFalse(actualResult.isComplete()); assertNull(actualResult.getInfomationContext()); } private void assertAllocateStatus(Index index, int shards, int replicas, AllocationRoutedStep step, Settings.Builder existingSettings, Settings.Builder node1Settings, Settings.Builder node2Settings, IndexRoutingTable.Builder indexRoutingTable, ClusterStateWaitStep.Result expectedResult) { IndexMetadata indexMetadata = IndexMetadata.builder(index.getName()).settings(existingSettings).numberOfShards(shards) .numberOfReplicas(replicas).build(); ImmutableOpenMap.Builder<String, IndexMetadata> indices = ImmutableOpenMap.<String, IndexMetadata> builder().fPut(index.getName(), indexMetadata); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE).metadata(Metadata.builder().indices(indices.build())) .nodes(DiscoveryNodes.builder() .add(DiscoveryNode.createLocal(node1Settings.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9200), "node1")) .add(DiscoveryNode.createLocal(node2Settings.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9201), "node2"))) .routingTable(RoutingTable.builder().add(indexRoutingTable).build()).build(); Result actualResult = step.isConditionMet(index, clusterState); assertEquals(expectedResult.isComplete(), actualResult.isComplete()); assertEquals(expectedResult.getInfomationContext(), actualResult.getInfomationContext()); } }
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AllocationRoutedStepTests.java
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.core.ilm; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.cluster.routing.UnassignedInfo; import org.elasticsearch.cluster.routing.UnassignedInfo.Reason; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.node.Node; import org.elasticsearch.xpack.core.ilm.ClusterStateWaitStep.Result; import org.elasticsearch.xpack.core.ilm.Step.StepKey; import java.util.Collections; import java.util.Map; import static org.elasticsearch.xpack.core.ilm.step.info.AllocationInfo.allShardsActiveAllocationInfo; import static org.elasticsearch.xpack.core.ilm.step.info.AllocationInfo.waitingForActiveShardsAllocationInfo; public class AllocationRoutedStepTests extends AbstractStepTestCase<AllocationRoutedStep> { @Override public AllocationRoutedStep createRandomInstance() { StepKey stepKey = randomStepKey(); StepKey nextStepKey = randomStepKey(); return new AllocationRoutedStep(stepKey, nextStepKey); } @Override public AllocationRoutedStep mutateInstance(AllocationRoutedStep instance) { StepKey key = instance.getKey(); StepKey nextKey = instance.getNextStepKey(); switch (between(0, 1)) { case 0: key = new StepKey(key.getPhase(), key.getAction(), key.getName() + randomAlphaOfLength(5)); break; case 1: nextKey = new StepKey(key.getPhase(), key.getAction(), key.getName() + randomAlphaOfLength(5)); break; default: throw new AssertionError("Illegal randomisation branch"); } return new AllocationRoutedStep(key, nextKey); } @Override public AllocationRoutedStep copyInstance(AllocationRoutedStep instance) { return new AllocationRoutedStep(instance.getKey(), instance.getNextStepKey()); } public void testConditionMet() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> requires = AllocateActionTests.randomAllocationRoutingMap(1, 5); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(true, null)); } public void testRequireConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> requires = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testClusterExcludeFiltersConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); IndexMetadata indexMetadata = IndexMetadata.builder(index.getName()).settings(existingSettings).numberOfShards(1) .numberOfReplicas(1).build(); ImmutableOpenMap.Builder<String, IndexMetadata> indices = ImmutableOpenMap.<String, IndexMetadata>builder().fPut(index.getName(), indexMetadata); Settings clusterSettings = Settings.builder() .put("cluster.routing.allocation.exclude._id", "node1") .build(); Settings.Builder nodeSettingsBuilder = Settings.builder(); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE) .metadata(Metadata.builder().indices(indices.build()).transientSettings(clusterSettings)) .nodes(DiscoveryNodes.builder() .add(DiscoveryNode.createLocal(nodeSettingsBuilder.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9200), "node1")) .add(DiscoveryNode.createLocal(nodeSettingsBuilder.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9201), "node2"))) .routingTable(RoutingTable.builder().add(indexRoutingTable).build()).build(); Result actualResult = step.isConditionMet(index, clusterState); Result expectedResult = new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(1, 1)); assertEquals(expectedResult.isComplete(), actualResult.isComplete()); assertEquals(expectedResult.getInfomationContext(), actualResult.getInfomationContext()); } public void testExcludeConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> excludes = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testIncludeConditionMetOnlyOneCopyAllocated() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = Collections.singletonMap(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + "foo", "bar"); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, Settings.builder(), indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testConditionNotMetDueToRelocation() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> requires = AllocateActionTests.randomAllocationRoutingMap(1, 5); Settings.Builder existingSettings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_PREFIX + "._id", "node1") .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); ShardRouting shardOnNode1 = TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED); shardOnNode1 = shardOnNode1.relocate("node3", 230); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(shardOnNode1) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); assertAllocateStatus(index, 1, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 2))); } public void testExecuteAllocateNotComplete() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 1), "node2", true, ShardRoutingState.STARTED)); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } public void testExecuteAllocateNotCompleteOnlyOneCopyAllocated() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); boolean primaryOnNode1 = randomBoolean(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", primaryOnNode1, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node2", primaryOnNode1 == false, ShardRoutingState.STARTED)); AllocationRoutedStep step = new AllocationRoutedStep(randomStepKey(), randomStepKey()); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/76633") public void testExecuteAllocateUnassigned() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); Map<String, String> excludes = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Map<String, String> requires = randomValueOtherThanMany(map -> map.keySet().stream().anyMatch(includes::containsKey) || map.keySet().stream().anyMatch(excludes::containsKey), () -> AllocateActionTests.randomAllocationRoutingMap(1, 5)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); includes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_INCLUDE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); excludes.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + k, v); }); requires.forEach((k, v) -> { existingSettings.put(IndexMetadata.INDEX_ROUTING_REQUIRE_GROUP_SETTING.getKey() + k, v); node1Settings.put(Node.NODE_ATTRIBUTES.getKey() + k, v); }); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 1), null, null, true, ShardRoutingState.UNASSIGNED, new UnassignedInfo(randomFrom(Reason.values()), "the shard is intentionally unassigned"))); logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", includes, excludes, requires); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 2, 0, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, waitingForActiveShardsAllocationInfo(0))); } /** * this tests the scenario where * * PUT index * { * "settings": { * "number_of_replicas": 0, * "number_of_shards": 1 * } * } * * PUT index/_settings * { * "number_of_replicas": 1, * "index.routing.allocation.include._name": "{node-name}" * } */ public void testExecuteReplicasNotAllocatedOnSingleNode() { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); Settings.Builder existingSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT.id) .put(IndexMetadata.SETTING_INDEX_UUID, index.getUUID()); Settings.Builder node1Settings = Settings.builder(); Settings.Builder node2Settings = Settings.builder(); IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), null, null, false, ShardRoutingState.UNASSIGNED, new UnassignedInfo(Reason.REPLICA_ADDED, "no attempt"))); AllocationRoutedStep step = createRandomInstance(); assertAllocateStatus(index, 1, 1, step, existingSettings, node1Settings, node2Settings, indexRoutingTable, new ClusterStateWaitStep.Result(false, waitingForActiveShardsAllocationInfo(1))); } public void testExecuteIndexMissing() throws Exception { Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE).build(); AllocationRoutedStep step = createRandomInstance(); Result actualResult = step.isConditionMet(index, clusterState); assertFalse(actualResult.isComplete()); assertNull(actualResult.getInfomationContext()); } private void assertAllocateStatus(Index index, int shards, int replicas, AllocationRoutedStep step, Settings.Builder existingSettings, Settings.Builder node1Settings, Settings.Builder node2Settings, IndexRoutingTable.Builder indexRoutingTable, ClusterStateWaitStep.Result expectedResult) { IndexMetadata indexMetadata = IndexMetadata.builder(index.getName()).settings(existingSettings).numberOfShards(shards) .numberOfReplicas(replicas).build(); ImmutableOpenMap.Builder<String, IndexMetadata> indices = ImmutableOpenMap.<String, IndexMetadata> builder().fPut(index.getName(), indexMetadata); ClusterState clusterState = ClusterState.builder(ClusterState.EMPTY_STATE).metadata(Metadata.builder().indices(indices.build())) .nodes(DiscoveryNodes.builder() .add(DiscoveryNode.createLocal(node1Settings.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9200), "node1")) .add(DiscoveryNode.createLocal(node2Settings.build(), new TransportAddress(TransportAddress.META_ADDRESS, 9201), "node2"))) .routingTable(RoutingTable.builder().add(indexRoutingTable).build()).build(); Result actualResult = step.isConditionMet(index, clusterState); assertEquals(expectedResult.isComplete(), actualResult.isComplete()); assertEquals(expectedResult.getInfomationContext(), actualResult.getInfomationContext()); } }
Fix UnassignedInfo generation in AllocationRoutedStepTests (#76684) This PR fixes the generation of `UnassignedInfo` in AllocationRoutedStepTests#testExecuteAllocateUnassigned to ensure that it will not trigger consistency-check assertions.
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AllocationRoutedStepTests.java
Fix UnassignedInfo generation in AllocationRoutedStepTests (#76684)
<ide><path>-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ilm/AllocationRoutedStepTests.java <ide> new ClusterStateWaitStep.Result(false, allShardsActiveAllocationInfo(0, 1))); <ide> } <ide> <del> @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/76633") <ide> public void testExecuteAllocateUnassigned() throws Exception { <ide> Index index = new Index(randomAlphaOfLengthBetween(1, 20), randomAlphaOfLengthBetween(1, 20)); <ide> Map<String, String> includes = AllocateActionTests.randomAllocationRoutingMap(1, 5); <ide> IndexRoutingTable.Builder indexRoutingTable = IndexRoutingTable.builder(index) <ide> .addShard(TestShardRouting.newShardRouting(new ShardId(index, 0), "node1", true, ShardRoutingState.STARTED)) <ide> .addShard(TestShardRouting.newShardRouting(new ShardId(index, 1), null, null, true, ShardRoutingState.UNASSIGNED, <del> new UnassignedInfo(randomFrom(Reason.values()), "the shard is intentionally unassigned"))); <add> TestShardRouting.randomUnassignedInfo("the shard is intentionally unassigned"))); <ide> <ide> logger.info("running test with routing configurations:\n\t includes: [{}]\n\t excludes: [{}]\n\t requires: [{}]", <ide> includes, excludes, requires);
Java
apache-2.0
83e25794c819fa9686baa30fa0b50a98f777d594
0
RayBa82/DVBViewerController,RayBa82/DVBViewerController
/* * Copyright © 2013 dvbviewer-controller Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dvbviewer.controller.ui.fragments; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import org.dvbviewer.controller.R; import org.dvbviewer.controller.data.DbConsts; import org.dvbviewer.controller.data.DbConsts.ChannelTbl; import org.dvbviewer.controller.entities.Channel; import org.dvbviewer.controller.entities.DVBViewerPreferences; import org.dvbviewer.controller.ui.base.CursorPagerAdapter; import org.dvbviewer.controller.ui.fragments.ChannelEpg.EpgDateInfo; import org.dvbviewer.controller.ui.widget.ActionToolbar; import org.dvbviewer.controller.utils.DateUtils; import org.dvbviewer.controller.utils.UIUtils; import java.lang.ref.WeakReference; import java.util.Date; /** * The Class EpgPager. */ public class EpgPager extends Fragment implements LoaderCallbacks<Cursor>, Toolbar.OnMenuItemClickListener { public static final String KEY_HIDE_OPTIONSMENU = EpgPager.class.getName() + "KEY_HIDE_OPTIONSMENU"; private long mGroupId = AdapterView.INVALID_POSITION; private int chanIndex = AdapterView.INVALID_POSITION; private ViewPager mPager; private PagerAdapter mAdapter; private OnPageChangeListener mOnPageChangeListener; private Boolean showFavs; private Cursor mEpgCursor; /* * (non-Javadoc) * * @see * com.actionbarsherlock.app.SherlockFragment#onAttach(android.app.Activity) */ @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnPageChangeListener) { mOnPageChangeListener = (OnPageChangeListener) context; } } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new PagerAdapter(getChildFragmentManager(), mEpgCursor); DVBViewerPreferences prefs = new DVBViewerPreferences(getActivity()); showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false); boolean showOptionsMenu = true; if (getArguments() != null){ showOptionsMenu = !getArguments().getBoolean(KEY_HIDE_OPTIONSMENU, false); } setHasOptionsMenu(showOptionsMenu); if (savedInstanceState == null) { if (getArguments() != null){ mGroupId = getArguments().containsKey(ChannelList.KEY_GROUP_ID) ? getArguments().getLong(ChannelList.KEY_GROUP_ID, mGroupId) : mGroupId; chanIndex = getArguments().containsKey(ChannelList.KEY_CHANNEL_INDEX) ? getArguments().getInt(ChannelList.KEY_CHANNEL_INDEX, chanIndex) : chanIndex; } } else { mGroupId = savedInstanceState.containsKey(ChannelList.KEY_GROUP_ID) ? savedInstanceState.getLong(ChannelList.KEY_GROUP_ID, mGroupId) : mGroupId; chanIndex = savedInstanceState.containsKey(ChannelList.KEY_CHANNEL_INDEX) ? savedInstanceState.getInt(ChannelList.KEY_CHANNEL_INDEX, chanIndex) : chanIndex; } } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mPager.setAdapter(mAdapter); mPager.setPageMargin((int) UIUtils.dipToPixel(getActivity(), 25)); mPager.setCurrentItem(chanIndex); mPager.addOnPageChangeListener(mOnPageChangeListener); getLoaderManager().initLoader(0, null, this); } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onViewCreated(android.view.View, * android.os.Bundle) */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPager = (ViewPager) view.findViewById(R.id.pager); } /* * (non-Javadoc) * * @see * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, * android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pager, container, false); ActionToolbar bootomBar = (ActionToolbar) v.findViewById(R.id.toolbar); bootomBar.inflateMenu(R.menu.channel_epg_bottom_bar); bootomBar.setOnMenuItemClickListener(this); return v; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(ChannelList.KEY_GROUP_ID, mGroupId); outState.putInt(ChannelList.KEY_CHANNEL_INDEX, mPager.getCurrentItem()); } /* * (non-Javadoc) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.channel_epg, menu); } /* * (non-Javadoc) */ @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int itemId = item.getItemId(); switch (itemId) { case R.id.menuRefresh: getActivity().supportInvalidateOptionsMenu(); ChannelEpg mCurrent; mCurrent = (ChannelEpg) mAdapter.instantiateItem(mPager, mPager.getCurrentItem()); mCurrent.refresh(true); break; default: return false; } return true; } /* * (non-Javadoc) */ @Override public boolean onMenuItemClick(MenuItem menuItem) { EpgDateInfo info = (EpgDateInfo) getActivity(); int itemId = menuItem.getItemId(); switch (itemId) { case R.id.menuPrev: info.setEpgDate(DateUtils.substractDay(info.getEpgDate())); info.setEpgDate(DateUtils.substractDay(info.getEpgDate())); case R.id.menuNext: info.setEpgDate(DateUtils.addDay(info.getEpgDate())); break; case R.id.menuToday: info.setEpgDate(new Date()); break; case R.id.menuNow: info.setEpgDate(DateUtils.setCurrentTime(info.getEpgDate())); break; case R.id.menuEvening: info.setEpgDate(DateUtils.setEveningTime(info.getEpgDate())); break; default: return false; } getActivity().supportInvalidateOptionsMenu(); ChannelEpg mCurrent; mCurrent = (ChannelEpg) mAdapter.instantiateItem(mPager, mPager.getCurrentItem()); mCurrent.refresh(true); return true; } /** * The Class PagerAdapter. */ class PagerAdapter extends CursorPagerAdapter { WeakReference<ChannelEpg> fragmentCache = new WeakReference<>(null); /** * Instantiates a new pager adapter. * * @param fm the fm */ public PagerAdapter(FragmentManager fm, Cursor cursor) { super(fm, cursor); mCursor = cursor; } /* * (non-Javadoc) * * @see android.support.v4.app.FragmentPagerAdapter#getItem(int) */ @Override public Fragment getItem(int position) { if (mCursor == null || mCursor.isClosed() || position == AdapterView.INVALID_POSITION) { return null; } mCursor.moveToPosition(position); final Channel chan = ChannelList.cursorToChannel(mCursor); final Bundle bundle = new Bundle(); bundle.putString(ChannelEpg.KEY_CHANNEL_NAME, chan.getName()); bundle.putLong(ChannelEpg.KEY_EPG_ID, chan.getEpgID()); bundle.putLong(ChannelEpg.KEY_CHANNEL_ID, chan.getChannelID()); bundle.putString(ChannelEpg.KEY_CHANNEL_LOGO, chan.getLogoUrl()); bundle.putInt(ChannelEpg.KEY_CHANNEL_POS, chan.getPosition()); bundle.putInt(ChannelEpg.KEY_FAV_POS, chan.getFavPosition()); final ChannelEpg channelEpg = (ChannelEpg) Fragment.instantiate(getActivity(), ChannelEpg.class.getName(), bundle); return channelEpg; } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); ChannelEpg chanEPG = (ChannelEpg) object; fragmentCache = new WeakReference<>(chanEPG); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } /* * (non-Javadoc) * * @see android.support.v4.view.PagerAdapter#getCount() */ @Override public int getCount() { return mCursor != null ? mCursor.getCount() : 0; } public Cursor getmCursor() { return mCursor; } public ChannelEpg getCurrentFragment(int position) { ChannelEpg result = fragmentCache.get(); return result; } } /** * Sets the position. * * @param position the new position */ public void setPosition(int position) { chanIndex = position; if (mPager != null) { mPager.setCurrentItem(chanIndex, false); } } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { StringBuilder selection = new StringBuilder(showFavs ? ChannelTbl.FLAGS + " & " + Channel.FLAG_FAV + "!= 0" : ChannelTbl.FLAGS + " & " + Channel.FLAG_ADDITIONAL_AUDIO + "== 0"); if (mGroupId > 0) { selection.append(" and "); if (showFavs) { selection.append(DbConsts.FavTbl.FAV_GROUP_ID).append(" = ").append(mGroupId); } else { selection.append(ChannelTbl.GROUP_ID).append(" = ").append(mGroupId); } } String orderBy; orderBy = showFavs ? ChannelTbl.FAV_POSITION : ChannelTbl.POSITION; return new CursorLoader(getActivity().getApplicationContext(), ChannelTbl.CONTENT_URI, null, selection.toString(), null, orderBy); } /* * (non-Javadoc) * * @see * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android * .support.v4.content.Loader, java.lang.Object) */ @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { mEpgCursor = cursor; mAdapter.changeCursor(mEpgCursor); mAdapter.notifyDataSetChanged(); mPager.setCurrentItem(chanIndex, false); } /* * (non-Javadoc) * * @see * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android * .support.v4.content.Loader) */ @Override public void onLoaderReset(Loader<Cursor> arg0) { } public void setGroupId(long groupId) { this.mGroupId = groupId; } public long getGroupId(){ return mGroupId; } public int getChanIndex(){ return chanIndex; } public void refresh(long groupId, int selectedPosition) { if (mGroupId != groupId){ mGroupId = groupId; chanIndex = selectedPosition; refresh(); } } private void refresh() { resetLoader(); } private void resetLoader() { DVBViewerPreferences prefs = new DVBViewerPreferences(getActivity()); showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false); mEpgCursor = null; mPager.setAdapter(null); mAdapter.notifyDataSetChanged(); mAdapter = new PagerAdapter(getChildFragmentManager(), mEpgCursor); mPager.setAdapter(mAdapter); getLoaderManager().destroyLoader(0); getLoaderManager().restartLoader(0, getArguments(), this); } public interface OnChannelChangedListener { void channelChanged(int groupIndex, int channelIndex); } }
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/EpgPager.java
/* * Copyright © 2013 dvbviewer-controller Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.dvbviewer.controller.ui.fragments; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import org.dvbviewer.controller.R; import org.dvbviewer.controller.data.DbConsts; import org.dvbviewer.controller.data.DbConsts.ChannelTbl; import org.dvbviewer.controller.entities.Channel; import org.dvbviewer.controller.entities.DVBViewerPreferences; import org.dvbviewer.controller.ui.base.CursorPagerAdapter; import org.dvbviewer.controller.ui.fragments.ChannelEpg.EpgDateInfo; import org.dvbviewer.controller.ui.widget.ActionToolbar; import org.dvbviewer.controller.utils.DateUtils; import org.dvbviewer.controller.utils.UIUtils; import java.lang.ref.WeakReference; import java.util.Date; /** * The Class EpgPager. */ public class EpgPager extends Fragment implements LoaderCallbacks<Cursor>, Toolbar.OnMenuItemClickListener { public static final String KEY_HIDE_OPTIONSMENU = EpgPager.class.getName() + "KEY_HIDE_OPTIONSMENU"; private long mGroupId = AdapterView.INVALID_POSITION; private int chanIndex = AdapterView.INVALID_POSITION; private ViewPager mPager; private PagerAdapter mAdapter; private OnPageChangeListener mOnPageChangeListener; private Boolean showFavs; private Cursor mEpgCursor; /* * (non-Javadoc) * * @see * com.actionbarsherlock.app.SherlockFragment#onAttach(android.app.Activity) */ @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnPageChangeListener) { mOnPageChangeListener = (OnPageChangeListener) context; } } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new PagerAdapter(getChildFragmentManager(), mEpgCursor); DVBViewerPreferences prefs = new DVBViewerPreferences(getActivity()); showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false); boolean showOptionsMenu = true; if (getArguments() != null){ showOptionsMenu = !getArguments().getBoolean(KEY_HIDE_OPTIONSMENU, false); } setHasOptionsMenu(showOptionsMenu); if (savedInstanceState == null) { if (getArguments() != null){ mGroupId = getArguments().containsKey(ChannelList.KEY_GROUP_ID) ? getArguments().getLong(ChannelList.KEY_GROUP_ID, mGroupId) : mGroupId; chanIndex = getArguments().containsKey(ChannelList.KEY_CHANNEL_INDEX) ? getArguments().getInt(ChannelList.KEY_CHANNEL_INDEX, chanIndex) : chanIndex; } } else { mGroupId = savedInstanceState.containsKey(ChannelList.KEY_GROUP_ID) ? savedInstanceState.getLong(ChannelList.KEY_GROUP_ID, mGroupId) : mGroupId; chanIndex = savedInstanceState.containsKey(ChannelList.KEY_CHANNEL_INDEX) ? savedInstanceState.getInt(ChannelList.KEY_CHANNEL_INDEX, chanIndex) : chanIndex; } } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle) */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mPager.setAdapter(mAdapter); mPager.setPageMargin((int) UIUtils.dipToPixel(getActivity(), 25)); mPager.setCurrentItem(chanIndex); mPager.addOnPageChangeListener(mOnPageChangeListener); getLoaderManager().initLoader(0, null, this); } /* * (non-Javadoc) * * @see android.support.v4.app.Fragment#onViewCreated(android.view.View, * android.os.Bundle) */ @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPager = (ViewPager) view.findViewById(R.id.pager); } /* * (non-Javadoc) * * @see * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, * android.view.ViewGroup, android.os.Bundle) */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.pager, null); ActionToolbar bootomBar = (ActionToolbar) v.findViewById(R.id.toolbar); bootomBar.inflateMenu(R.menu.channel_epg_bottom_bar); bootomBar.setOnMenuItemClickListener(this); return v; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(ChannelList.KEY_GROUP_ID, mGroupId); outState.putInt(ChannelList.KEY_CHANNEL_INDEX, mPager.getCurrentItem()); } /* * (non-Javadoc) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.channel_epg, menu); } /* * (non-Javadoc) */ @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int itemId = item.getItemId(); switch (itemId) { case R.id.menuRefresh: getActivity().supportInvalidateOptionsMenu(); ChannelEpg mCurrent; mCurrent = (ChannelEpg) mAdapter.instantiateItem(mPager, mPager.getCurrentItem()); mCurrent.refresh(true); break; default: return false; } return true; } /* * (non-Javadoc) */ @Override public boolean onMenuItemClick(MenuItem menuItem) { EpgDateInfo info = (EpgDateInfo) getActivity(); int itemId = menuItem.getItemId(); switch (itemId) { case R.id.menuPrev: info.setEpgDate(DateUtils.substractDay(info.getEpgDate())); info.setEpgDate(DateUtils.substractDay(info.getEpgDate())); case R.id.menuNext: info.setEpgDate(DateUtils.addDay(info.getEpgDate())); break; case R.id.menuToday: info.setEpgDate(new Date()); break; case R.id.menuNow: info.setEpgDate(DateUtils.setCurrentTime(info.getEpgDate())); break; case R.id.menuEvening: info.setEpgDate(DateUtils.setEveningTime(info.getEpgDate())); break; default: return false; } getActivity().supportInvalidateOptionsMenu(); ChannelEpg mCurrent; mCurrent = (ChannelEpg) mAdapter.instantiateItem(mPager, mPager.getCurrentItem()); mCurrent.refresh(true); return true; } /** * The Class PagerAdapter. */ class PagerAdapter extends CursorPagerAdapter { WeakReference<ChannelEpg> fragmentCache = new WeakReference<ChannelEpg>(null); /** * Instantiates a new pager adapter. * * @param fm the fm */ public PagerAdapter(FragmentManager fm, Cursor cursor) { super(fm, cursor); mCursor = cursor; } /* * (non-Javadoc) * * @see android.support.v4.app.FragmentPagerAdapter#getItem(int) */ @Override public Fragment getItem(int position) { if (mCursor == null || mCursor.isClosed()) { return null; } mCursor.moveToPosition(position); final Channel chan = ChannelList.cursorToChannel(mCursor); final Bundle bundle = new Bundle(); bundle.putString(ChannelEpg.KEY_CHANNEL_NAME, chan.getName()); bundle.putLong(ChannelEpg.KEY_EPG_ID, chan.getEpgID()); bundle.putLong(ChannelEpg.KEY_CHANNEL_ID, chan.getChannelID()); bundle.putString(ChannelEpg.KEY_CHANNEL_LOGO, chan.getLogoUrl()); bundle.putInt(ChannelEpg.KEY_CHANNEL_POS, chan.getPosition()); bundle.putInt(ChannelEpg.KEY_FAV_POS, chan.getFavPosition()); final ChannelEpg channelEpg = (ChannelEpg) Fragment.instantiate(getActivity(), ChannelEpg.class.getName(), bundle); return channelEpg; } @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); ChannelEpg chanEPG = (ChannelEpg) object; fragmentCache = new WeakReference<>(chanEPG); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } /* * (non-Javadoc) * * @see android.support.v4.view.PagerAdapter#getCount() */ @Override public int getCount() { return mCursor != null ? mCursor.getCount() : 0; } public Cursor getmCursor() { return mCursor; } public ChannelEpg getCurrentFragment(int position) { ChannelEpg result = fragmentCache.get(); return result; } } /** * Sets the position. * * @param position the new position */ public void setPosition(int position) { chanIndex = position; if (mPager != null) { mPager.setCurrentItem(chanIndex, false); } } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) { StringBuilder selection = new StringBuilder(showFavs ? ChannelTbl.FLAGS + " & " + Channel.FLAG_FAV + "!= 0" : ChannelTbl.FLAGS + " & " + Channel.FLAG_ADDITIONAL_AUDIO + "== 0"); if (mGroupId > 0) { selection.append(" and "); if (showFavs) { selection.append(DbConsts.FavTbl.FAV_GROUP_ID).append(" = ").append(mGroupId); } else { selection.append(ChannelTbl.GROUP_ID).append(" = ").append(mGroupId); } } String orderBy; orderBy = showFavs ? ChannelTbl.FAV_POSITION : ChannelTbl.POSITION; return new CursorLoader(getActivity().getApplicationContext(), ChannelTbl.CONTENT_URI, null, selection.toString(), null, orderBy); } /* * (non-Javadoc) * * @see * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android * .support.v4.content.Loader, java.lang.Object) */ @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) { mEpgCursor = cursor; mAdapter.changeCursor(mEpgCursor); mAdapter.notifyDataSetChanged(); mPager.setCurrentItem(chanIndex, false); } /* * (non-Javadoc) * * @see * android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android * .support.v4.content.Loader) */ @Override public void onLoaderReset(Loader<Cursor> arg0) { } public void setGroupId(long groupId) { this.mGroupId = groupId; } public long getGroupId(){ return mGroupId; } public int getChanIndex(){ return chanIndex; } public void refresh(long groupId, int selectedPosition) { if (mGroupId != groupId){ mGroupId = groupId; chanIndex = selectedPosition; refresh(); } } private void refresh() { resetLoader(); } private void resetLoader() { DVBViewerPreferences prefs = new DVBViewerPreferences(getActivity()); showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false); mEpgCursor = null; mPager.setAdapter(null); mAdapter.notifyDataSetChanged(); mAdapter = new PagerAdapter(getChildFragmentManager(), mEpgCursor); mPager.setAdapter(mAdapter); getLoaderManager().destroyLoader(0); getLoaderManager().restartLoader(0, getArguments(), this); } public interface OnChannelChangedListener { void channelChanged(int groupIndex, int channelIndex); } }
Issue #48 prevent access to invalid cursor positions
dvbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/EpgPager.java
Issue #48 prevent access to invalid cursor positions
<ide><path>vbViewerController/src/main/java/org/dvbviewer/controller/ui/fragments/EpgPager.java <ide> */ <ide> @Override <ide> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { <del> View v = inflater.inflate(R.layout.pager, null); <add> View v = inflater.inflate(R.layout.pager, container, false); <ide> ActionToolbar bootomBar = (ActionToolbar) v.findViewById(R.id.toolbar); <ide> bootomBar.inflateMenu(R.menu.channel_epg_bottom_bar); <ide> bootomBar.setOnMenuItemClickListener(this); <ide> */ <ide> class PagerAdapter extends CursorPagerAdapter { <ide> <del> WeakReference<ChannelEpg> fragmentCache = new WeakReference<ChannelEpg>(null); <add> WeakReference<ChannelEpg> fragmentCache = new WeakReference<>(null); <ide> <ide> /** <ide> * Instantiates a new pager adapter. <ide> */ <ide> @Override <ide> public Fragment getItem(int position) { <del> if (mCursor == null || mCursor.isClosed()) { <add> if (mCursor == null || mCursor.isClosed() || position == AdapterView.INVALID_POSITION) { <ide> return null; <ide> } <ide> mCursor.moveToPosition(position);
Java
apache-2.0
48c9bbaf023d6f9e9b567b40091f60bc3c4c9797
0
cosmo0920/flume-ng-fluentd-sink
package com.github.cosmo0920.fluentd.flume.plugins; import org.apache.flume.Channel; import org.apache.flume.ChannelException; import org.apache.flume.Context; import org.apache.flume.CounterGroup; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.sink.AbstractSink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.komamitsu.fluency.Fluency; import java.io.IOException; import com.google.common.base.Preconditions; public class FluentdSink extends AbstractSink implements Configurable { private static final Logger logger = LoggerFactory.getLogger(FluentdSink.class); private static final int DEFAULT_PORT = 24424; private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_TAG = "flume.fluentd.sink"; private String hostname; private int port; private String tag; private Fluency fluentLogger; // TODO: extract this member to other class for safety. private CounterGroup counterGroup; public Fluency setupFluentdLogger(String hostname, int port) throws IOException { return Fluency.defaultFluency(hostname, port, new Fluency.Config()); } public FluentdSink() { counterGroup = new CounterGroup(); } public void configure(Context context) { hostname = context.getString("hostname"); String portStr = context.getString("port"); tag = context.getString("tag"); if (portStr != null) { port = Integer.parseInt(portStr); } else { port = DEFAULT_PORT; } if (hostname == null) { hostname = DEFAULT_HOST; } if (tag == null) { tag = DEFAULT_TAG; } Preconditions.checkState(hostname != null, "No hostname specified"); Preconditions.checkState(tag != null, "No tag specified"); } private void closeFluentdLogger() { if (this.fluentLogger != null) { try { this.fluentLogger.close(); } catch (IOException e) { // Do nothing. } } } @Override public void start() { logger.info("Fluentd sink starting"); try { this.fluentLogger = setupFluentdLogger(this.hostname, this.port); } catch (IOException e) { logger.error("Unable to create Fluentd logger using hostname:" + hostname + " port:" + port + ". Exception follows.", e); closeFluentdLogger(); return; // FIXME: mark this plugin as failed. } super.start(); logger.debug("Fluentd sink {} started", this.getName()); } @Override public void stop() { logger.info("Fluentd sink {} stopping", this.getName()); closeFluentdLogger(); super.stop(); logger.debug("Fluentd sink {} stopped. Metrics:{}", this.getName(), counterGroup); } @Override public Status process() throws EventDeliveryException { Status status = Status.READY; Channel channel = getChannel(); Transaction transaction = channel.getTransaction(); try { transaction.begin(); Event event = channel.take(); if (event == null) { counterGroup.incrementAndGet("event.empty"); status = Status.BACKOFF; } else { // TODO: send info Fluentd. counterGroup.incrementAndGet("event.fluentd"); } transaction.commit(); } catch (ChannelException e) { transaction.rollback(); logger.error( "Unable to get event from channel. Exception follows.", e); status = Status.BACKOFF; } catch (Exception e) { transaction.rollback(); logger.error( "Unable to communicate with Fluentd. Exception follows.", e); status = Status.BACKOFF; // TODO: destroy connection to Fluentd. } finally { transaction.close(); } return status; } }
src/main/java/com/github/cosmo0920/fluentd/flume/plugins/FluentdSink.java
package com.github.cosmo0920.fluentd.flume.plugins; import org.apache.flume.Channel; import org.apache.flume.ChannelException; import org.apache.flume.Context; import org.apache.flume.CounterGroup; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.sink.AbstractSink; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; public class FluentdSink extends AbstractSink implements Configurable { private static final Logger logger = LoggerFactory.getLogger(FluentdSink.class); private static final int DEFAULT_PORT = 24424; private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_TAG = "flume.fluentd.sink"; private String hostname; private Integer port; private String tag; private CounterGroup counterGroup; public void configure(Context context) { hostname = context.getString("hostname"); String portStr = context.getString("port"); tag = context.getString("tag"); if (portStr != null) { port = Integer.parseInt(portStr); } else { port = DEFAULT_PORT; } if (hostname == null) { hostname = DEFAULT_HOST; } if (tag == null) { tag = DEFAULT_TAG; } Preconditions.checkState(hostname != null, "No hostname specified"); Preconditions.checkState(tag != null, "No tag specified"); } @Override public void start() { logger.info("Fluentd sink starting"); super.start(); logger.debug("Fluentd sink {} started", this.getName()); } @Override public void stop() { logger.info("Fluentd sink {} stopping", this.getName()); super.stop(); logger.debug("Fluentd sink {} stopped. Metrics:{}", this.getName(), counterGroup); } @Override public Status process() throws EventDeliveryException { Status status = Status.READY; return status; } }
Create Fluentd logger TODOs: * Send event body into Fluentd * Write test code
src/main/java/com/github/cosmo0920/fluentd/flume/plugins/FluentdSink.java
Create Fluentd logger
<ide><path>rc/main/java/com/github/cosmo0920/fluentd/flume/plugins/FluentdSink.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <add>import org.komamitsu.fluency.Fluency; <add> <add>import java.io.IOException; <add> <ide> import com.google.common.base.Preconditions; <ide> <ide> public class FluentdSink extends AbstractSink implements Configurable { <ide> private static final String DEFAULT_TAG = "flume.fluentd.sink"; <ide> <ide> private String hostname; <del> private Integer port; <add> private int port; <ide> private String tag; <add> private Fluency fluentLogger; // TODO: extract this member to other class for safety. <ide> <ide> private CounterGroup counterGroup; <add> <add> public Fluency setupFluentdLogger(String hostname, int port) throws IOException { <add> return Fluency.defaultFluency(hostname, port, new Fluency.Config()); <add> } <add> <add> public FluentdSink() { <add> counterGroup = new CounterGroup(); <add> } <ide> <ide> public void configure(Context context) { <ide> hostname = context.getString("hostname"); <ide> Preconditions.checkState(tag != null, "No tag specified"); <ide> } <ide> <add> private void closeFluentdLogger() { <add> if (this.fluentLogger != null) { <add> try { <add> this.fluentLogger.close(); <add> } catch (IOException e) { <add> // Do nothing. <add> } <add> } <add> } <add> <ide> @Override <ide> public void start() { <ide> logger.info("Fluentd sink starting"); <add> <add> try { <add> this.fluentLogger = setupFluentdLogger(this.hostname, this.port); <add> } catch (IOException e) { <add> logger.error("Unable to create Fluentd logger using hostname:" <add> + hostname + " port:" + port + ". Exception follows.", e); <add> <add> closeFluentdLogger(); <add> <add> return; // FIXME: mark this plugin as failed. <add> } <ide> <ide> super.start(); <ide> <ide> public void stop() { <ide> logger.info("Fluentd sink {} stopping", this.getName()); <ide> <add> closeFluentdLogger(); <add> <ide> super.stop(); <ide> <ide> logger.debug("Fluentd sink {} stopped. Metrics:{}", this.getName(), counterGroup); <ide> @Override <ide> public Status process() throws EventDeliveryException { <ide> Status status = Status.READY; <add> Channel channel = getChannel(); <add> Transaction transaction = channel.getTransaction(); <add> <add> try { <add> transaction.begin(); <add> <add> Event event = channel.take(); <add> <add> if (event == null) { <add> counterGroup.incrementAndGet("event.empty"); <add> status = Status.BACKOFF; <add> } else { <add> // TODO: send info Fluentd. <add> counterGroup.incrementAndGet("event.fluentd"); <add> } <add> <add> transaction.commit(); <add> <add> } catch (ChannelException e) { <add> transaction.rollback(); <add> logger.error( <add> "Unable to get event from channel. Exception follows.", e); <add> status = Status.BACKOFF; <add> } catch (Exception e) { <add> transaction.rollback(); <add> logger.error( <add> "Unable to communicate with Fluentd. Exception follows.", <add> e); <add> status = Status.BACKOFF; <add> // TODO: destroy connection to Fluentd. <add> } finally { <add> transaction.close(); <add> } <ide> <ide> return status; <ide> }
Java
apache-2.0
9e4dbdc9da142306717d87c310f1e67bee26ea10
0
inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service
/* * Copyright 2012 Shared Learning Collaborative, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.ingestion.transformation.normalization.did; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.slc.sli.common.domain.EmbeddedDocumentRelations; import org.slc.sli.common.domain.NaturalKeyDescriptor; import org.slc.sli.common.util.uuid.UUIDGeneratorStrategy; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.transformation.normalization.IdResolutionException; import org.slc.sli.ingestion.validation.ErrorReport; import org.slc.sli.validation.SchemaRepository; /** * Resolver for deterministic id resolution. * * @author jtully * @author vmcglaughlin * */ public class DeterministicIdResolver { @Autowired @Qualifier("deterministicUUIDGeneratorStrategy") private UUIDGeneratorStrategy uuidGeneratorStrategy; private DidSchemaParser didSchemaParser; @Autowired private DidEntityConfigReader didConfigReader; @Autowired private SchemaRepository schemaRepository; private static final Logger LOG = LoggerFactory.getLogger(DeterministicIdResolver.class); private static final String BODY_PATH = "body."; private static final String PATH_SEPARATOR = "\\."; public void resolveInternalIds(Entity entity, String tenantId, ErrorReport errorReport) { resolveInternalIdsImpl(entity, tenantId, true, errorReport); } public void resolveInternalIds(Entity entity, String tenantId, boolean addContext, ErrorReport errorReport) { resolveInternalIdsImpl(entity, tenantId, addContext, errorReport); } public void resolveInternalIdsImpl(Entity entity, String tenantId, boolean addContext, ErrorReport errorReport) { DidEntityConfig entityConfig = getEntityConfig(entity.getType()); if (entityConfig == null) { return; } if (entityConfig.getReferenceSources() == null || entityConfig.getReferenceSources().isEmpty()) { LOG.debug("Entity configuration contains no references --> returning..."); return; } String referenceEntityType = ""; String sourceRefPath = ""; for (DidRefSource didRefSource : entityConfig.getReferenceSources()) { try { referenceEntityType = didRefSource.getEntityType(); sourceRefPath = didRefSource.getSourceRefPath(); handleDeterministicIdForReference(entity, didRefSource, tenantId); } catch (IdResolutionException e) { handleException(sourceRefPath, entity.getType(), referenceEntityType, e, errorReport); } } } private DidEntityConfig getEntityConfig(String entityType) { //use the json config if there is one DidEntityConfig entityConfig = didConfigReader.getDidEntityConfiguration(entityType); if (entityConfig == null) { entityConfig = didSchemaParser.getEntityConfigs().get(entityType); } return entityConfig; } private DidRefConfig getRefConfig(String refType) { return didSchemaParser.getRefConfigs().get(refType); } private void handleDeterministicIdForReference(Entity entity, DidRefSource didRefSource, String collectionName, String tenantId, boolean addContext) throws IdResolutionException { String entityType = didRefSource.getEntityType(); String sourceRefPath = didRefSource.getSourceRefPath(); DidRefConfig didRefConfig = getRefConfig(entityType); if (didRefConfig == null) { return; } //handle case of references within embedded lists of objects (for assessments) //split source ref path and look for lists in embedded objects String strippedRefPath = sourceRefPath.replaceFirst(BODY_PATH, ""); String[] pathParts = strippedRefPath.split(PATH_SEPARATOR); String refObjName = pathParts[pathParts.length-1]; //get a list of the parentNodes List<Map<String, Object>> parentNodes = new ArrayList<Map<String, Object>>(); extractReferenceParentNodes(parentNodes, entity.getBody(), pathParts, 0); //resolve and set all the parentNodes for (Map<String, Object> node : parentNodes) { Object resolvedRef = resolveReference(node.get(refObjName), didRefSource.isOptional(), didRefConfig, tenantId); if (resolvedRef != null) { node.put(refObjName, resolvedRef); } } } /** * Recursive extraction of all parent nodes in the entity that contain the reference * @throws IdResolutionException */ @SuppressWarnings("unchecked") private void extractReferenceParentNodes(List<Map<String, Object>> parentNodes, Map<String, Object> curNode, String[] pathParts, int level) throws IdResolutionException { String nextNodeName = pathParts[level]; if (level >= pathParts.length-1) { parentNodes.add(curNode); } else { Object nextNode = curNode.get(nextNodeName); if (nextNode instanceof List) { List<Object> nodeList = (List<Object>) nextNode; for (Object nodeObj : nodeList) { if (nodeObj instanceof Map) { extractReferenceParentNodes(parentNodes, (Map<String, Object>) nodeObj, pathParts, level+1); } } } else if (nextNode instanceof Map) { extractReferenceParentNodes(parentNodes, (Map<String, Object>) nextNode, pathParts, level+1); } } } private Object resolveReference(Object referenceObject, boolean isOptional, DidRefConfig didRefConfig, String tenantId) throws IdResolutionException { String refType = didRefConfig.getEntityType(); if (referenceObject == null) { // ignore an empty reference if it is optional if (isOptional) { return null; } else { throw new IdResolutionException("Missing required reference", refType, null); } } if (referenceObject instanceof List) { // handle a list of reference objects @SuppressWarnings("unchecked") List<Object> refList = (List<Object>) referenceObject; List<String> uuidList = new ArrayList<String>(); for (Object reference : refList) { @SuppressWarnings("unchecked") String uuid = getId((Map<String, Object>) reference, tenantId, didRefConfig); if (uuid != null && !uuid.isEmpty()) { uuidList.add(uuid); } else { throw new IdResolutionException("Null or empty deterministic id generated", refType, uuid); } } return uuidList; } else if (referenceObject instanceof Map) { // handle a single reference object @SuppressWarnings("unchecked") Map<String, Object> reference = (Map<String, Object>) referenceObject; String uuid = getId(reference, tenantId, didRefConfig); if (uuid != null && !uuid.isEmpty()) { return uuid; } else { throw new IdResolutionException("Null or empty deterministic id generated", refType, uuid); } } else { throw new IdResolutionException("Unsupported reference object type", refType, null); } } private Object getProperty(Object bean, String sourceRefPath) throws IdResolutionException { Object referenceObject; try { referenceObject = PropertyUtils.getProperty(bean, sourceRefPath); } catch (IllegalArgumentException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (IllegalAccessException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (InvocationTargetException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (NoSuchMethodException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } return referenceObject; } private void setProperty(Object bean, String fieldPath, Object uuid) throws IdResolutionException { try { PropertyUtils.setProperty(bean, fieldPath, uuid); } catch (IllegalAccessException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } catch (InvocationTargetException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } catch (NoSuchMethodException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } } private void handleException(String sourceRefPath, String entityType, String referenceType, Exception e, ErrorReport errorReport) { LOG.error("Error accessing indexed bean property " + sourceRefPath + " for bean " + entityType, e); String errorMessage = "ERROR: Failed to resolve a deterministic id" + "\n Entity " + entityType + ": Reference to " + referenceType + " is incomplete because the following reference field is not resolved: " + sourceRefPath; errorReport.error(errorMessage, this); } // function which, given reference type map (source object) and refConfig, return a did private String getId(Map<String, Object> reference, String tenantId, DidRefConfig didRefConfig) throws IdResolutionException { if (didRefConfig.getEntityType() == null || didRefConfig.getEntityType().isEmpty()) { return null; } if (didRefConfig.getKeyFields() == null || didRefConfig.getKeyFields().isEmpty()) { return null; } Map<String, String> naturalKeys = new HashMap<String, String>(); for (KeyFieldDef keyFieldDef : didRefConfig.getKeyFields()) { // populate naturalKeys Object value = null; if (keyFieldDef.getRefConfig() != null) { Object nestedRef = getProperty(reference, keyFieldDef.getValueSource()); if (nestedRef == null) { if (keyFieldDef.isOptional() == false) { throw new IdResolutionException("No value found for required reference", keyFieldDef.getValueSource(), ""); } else { // since it's an optional field, replace it with "" in the natural key list value = ""; } // otherwise, continue to end of loop with null 'value' } else { if (nestedRef instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> nestedRefMap = (Map<String, Object>) nestedRef; value = getId(nestedRefMap, tenantId, keyFieldDef.getRefConfig()); } else { throw new IdResolutionException("Non-map value found from entity", keyFieldDef.getValueSource(), ""); } } } else { value = getProperty(reference, keyFieldDef.getValueSource()); } String fieldName = keyFieldDef.getKeyFieldName(); // don't add null or empty keys to the naturalKeys map if (fieldName != null && !fieldName.isEmpty() && (value != null || keyFieldDef.isOptional())) { naturalKeys.put(fieldName, value == null ? "" : value.toString()); } else { // } } // no natural keys found if (naturalKeys.isEmpty()) { return null; } // TODO: need to verify this String parentId = null; String entityType = didRefConfig.getEntityType(); if (EmbeddedDocumentRelations.getSubDocuments().contains(entityType)) { String parentKey = EmbeddedDocumentRelations.getParentFieldReference(entityType); parentId = naturalKeys.get(parentKey); } NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(naturalKeys, tenantId, didRefConfig.getEntityType(), parentId); return uuidGeneratorStrategy.generateId(naturalKeyDescriptor); } public DidSchemaParser getDidSchemaParser() { return didSchemaParser; } public void setDidSchemaParser(DidSchemaParser didSchemaParser) { this.didSchemaParser = didSchemaParser; } }
sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/normalization/did/DeterministicIdResolver.java
/* * Copyright 2012 Shared Learning Collaborative, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.ingestion.transformation.normalization.did; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.slc.sli.common.domain.EmbeddedDocumentRelations; import org.slc.sli.common.domain.NaturalKeyDescriptor; import org.slc.sli.common.util.uuid.UUIDGeneratorStrategy; import org.slc.sli.domain.Entity; import org.slc.sli.ingestion.transformation.normalization.IdResolutionException; import org.slc.sli.ingestion.validation.ErrorReport; import org.slc.sli.validation.SchemaRepository; /** * Resolver for deterministic id resolution. * * @author jtully * @author vmcglaughlin * */ public class DeterministicIdResolver { @Autowired @Qualifier("deterministicUUIDGeneratorStrategy") private UUIDGeneratorStrategy uuidGeneratorStrategy; private DidSchemaParser didSchemaParser; @Autowired private DidEntityConfigReader didConfigReader; @Autowired private SchemaRepository schemaRepository; private static final Logger LOG = LoggerFactory.getLogger(DeterministicIdResolver.class); private static final String BODY_PATH = "body."; private static final String PATH_SEPARATOR = "\\."; public void resolveInternalIds(Entity entity, String tenantId, ErrorReport errorReport) { resolveInternalIdsImpl(entity, tenantId, true, errorReport); } public void resolveInternalIds(Entity entity, String tenantId, boolean addContext, ErrorReport errorReport) { resolveInternalIdsImpl(entity, tenantId, addContext, errorReport); } public void resolveInternalIdsImpl(Entity entity, String tenantId, boolean addContext, ErrorReport errorReport) { DidEntityConfig entityConfig = getEntityConfig(entity.getType()); if (entityConfig == null) { return; } if (entityConfig.getReferenceSources() == null || entityConfig.getReferenceSources().isEmpty()) { LOG.debug("Entity configuration contains no references --> returning..."); return; } String referenceEntityType = ""; String sourceRefPath = ""; for (DidRefSource didRefSource : entityConfig.getReferenceSources()) { try { referenceEntityType = didRefSource.getEntityType(); sourceRefPath = didRefSource.getSourceRefPath(); handleDeterministicIdForReference(entity, didRefSource, tenantId); } catch (IdResolutionException e) { handleException(sourceRefPath, entity.getType(), referenceEntityType, e, errorReport); } } } private DidEntityConfig getEntityConfig(String entityType) { //use the json config if there is one DidEntityConfig entityConfig = didConfigReader.getDidEntityConfiguration(entityType); if (entityConfig == null) { entityConfig = didSchemaParser.getEntityConfigs().get(entityType); } return entityConfig; } private DidRefConfig getRefConfig(String refType) { return didSchemaParser.getRefConfigs().get(refType); } <<<<<<< HEAD private void handleDeterministicIdForReference(Entity entity, DidRefSource didRefSource, String collectionName, String tenantId, boolean addContext) throws IdResolutionException { ======= private void handleDeterministicIdForReference(Entity entity, DidRefSource didRefSource, String tenantId) throws IdResolutionException { >>>>>>> master String entityType = didRefSource.getEntityType(); String sourceRefPath = didRefSource.getSourceRefPath(); DidRefConfig didRefConfig = getRefConfig(entityType); if (didRefConfig == null) { return; } //handle case of references within embedded lists of objects (for assessments) //split source ref path and look for lists in embedded objects String strippedRefPath = sourceRefPath.replaceFirst(BODY_PATH, ""); String[] pathParts = strippedRefPath.split(PATH_SEPARATOR); String refObjName = pathParts[pathParts.length-1]; //get a list of the parentNodes List<Map<String, Object>> parentNodes = new ArrayList<Map<String, Object>>(); extractReferenceParentNodes(parentNodes, entity.getBody(), pathParts, 0); //resolve and set all the parentNodes for (Map<String, Object> node : parentNodes) { Object resolvedRef = resolveReference(node.get(refObjName), didRefSource.isOptional(), didRefConfig, tenantId); if (resolvedRef != null) { node.put(refObjName, resolvedRef); } } } /** * Recursive extraction of all parent nodes in the entity that contain the reference * @throws IdResolutionException */ @SuppressWarnings("unchecked") private void extractReferenceParentNodes(List<Map<String, Object>> parentNodes, Map<String, Object> curNode, String[] pathParts, int level) throws IdResolutionException { String nextNodeName = pathParts[level]; if (level >= pathParts.length-1) { parentNodes.add(curNode); } else { Object nextNode = curNode.get(nextNodeName); if (nextNode instanceof List) { List<Object> nodeList = (List<Object>) nextNode; for (Object nodeObj : nodeList) { if (nodeObj instanceof Map) { extractReferenceParentNodes(parentNodes, (Map<String, Object>) nodeObj, pathParts, level+1); } } } else if (nextNode instanceof Map) { extractReferenceParentNodes(parentNodes, (Map<String, Object>) nextNode, pathParts, level+1); } } } private Object resolveReference(Object referenceObject, boolean isOptional, DidRefConfig didRefConfig, String tenantId) throws IdResolutionException { String refType = didRefConfig.getEntityType(); if (referenceObject == null) { // ignore an empty reference if it is optional if (isOptional) { return null; } else { throw new IdResolutionException("Missing required reference", refType, null); } } if (referenceObject instanceof List) { // handle a list of reference objects @SuppressWarnings("unchecked") List<Object> refList = (List<Object>) referenceObject; List<String> uuidList = new ArrayList<String>(); for (Object reference : refList) { @SuppressWarnings("unchecked") String uuid = getId((Map<String, Object>) reference, tenantId, didRefConfig); if (uuid != null && !uuid.isEmpty()) { uuidList.add(uuid); } else { throw new IdResolutionException("Null or empty deterministic id generated", refType, uuid); } } return uuidList; } else if (referenceObject instanceof Map) { // handle a single reference object @SuppressWarnings("unchecked") Map<String, Object> reference = (Map<String, Object>) referenceObject; String uuid = getId(reference, tenantId, didRefConfig); if (uuid != null && !uuid.isEmpty()) { return uuid; } else { throw new IdResolutionException("Null or empty deterministic id generated", refType, uuid); } } else { throw new IdResolutionException("Unsupported reference object type", refType, null); } } private Object getProperty(Object bean, String sourceRefPath) throws IdResolutionException { Object referenceObject; try { referenceObject = PropertyUtils.getProperty(bean, sourceRefPath); } catch (IllegalArgumentException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (IllegalAccessException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (InvocationTargetException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } catch (NoSuchMethodException e) { throw new IdResolutionException("Unable to pull reference object from entity", sourceRefPath, null, e); } return referenceObject; } private void setProperty(Object bean, String fieldPath, Object uuid) throws IdResolutionException { try { PropertyUtils.setProperty(bean, fieldPath, uuid); } catch (IllegalAccessException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } catch (InvocationTargetException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } catch (NoSuchMethodException e) { throw new IdResolutionException("Unable to set reference object for entity", fieldPath, uuid.toString(), e); } } private void handleException(String sourceRefPath, String entityType, String referenceType, Exception e, ErrorReport errorReport) { LOG.error("Error accessing indexed bean property " + sourceRefPath + " for bean " + entityType, e); String errorMessage = "ERROR: Failed to resolve a deterministic id" + "\n Entity " + entityType + ": Reference to " + referenceType + " is incomplete because the following reference field is not resolved: " + sourceRefPath; errorReport.error(errorMessage, this); } // function which, given reference type map (source object) and refConfig, return a did private String getId(Map<String, Object> reference, String tenantId, DidRefConfig didRefConfig) throws IdResolutionException { if (didRefConfig.getEntityType() == null || didRefConfig.getEntityType().isEmpty()) { return null; } if (didRefConfig.getKeyFields() == null || didRefConfig.getKeyFields().isEmpty()) { return null; } Map<String, String> naturalKeys = new HashMap<String, String>(); for (KeyFieldDef keyFieldDef : didRefConfig.getKeyFields()) { // populate naturalKeys Object value = null; if (keyFieldDef.getRefConfig() != null) { Object nestedRef = getProperty(reference, keyFieldDef.getValueSource()); if (nestedRef == null) { if (keyFieldDef.isOptional() == false) { throw new IdResolutionException("No value found for required reference", keyFieldDef.getValueSource(), ""); } else { // since it's an optional field, replace it with "" in the natural key list value = ""; } // otherwise, continue to end of loop with null 'value' } else { if (nestedRef instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> nestedRefMap = (Map<String, Object>) nestedRef; value = getId(nestedRefMap, tenantId, keyFieldDef.getRefConfig()); } else { throw new IdResolutionException("Non-map value found from entity", keyFieldDef.getValueSource(), ""); } } } else { value = getProperty(reference, keyFieldDef.getValueSource()); } String fieldName = keyFieldDef.getKeyFieldName(); // don't add null or empty keys to the naturalKeys map if (fieldName != null && !fieldName.isEmpty() && (value != null || keyFieldDef.isOptional())) { naturalKeys.put(fieldName, value == null ? "" : value.toString()); } else { // } } // no natural keys found if (naturalKeys.isEmpty()) { return null; } // TODO: need to verify this String parentId = null; String entityType = didRefConfig.getEntityType(); if (EmbeddedDocumentRelations.getSubDocuments().contains(entityType)) { String parentKey = EmbeddedDocumentRelations.getParentFieldReference(entityType); parentId = naturalKeys.get(parentKey); } NaturalKeyDescriptor naturalKeyDescriptor = new NaturalKeyDescriptor(naturalKeys, tenantId, didRefConfig.getEntityType(), parentId); return uuidGeneratorStrategy.generateId(naturalKeyDescriptor); } public DidSchemaParser getDidSchemaParser() { return didSchemaParser; } public void setDidSchemaParser(DidSchemaParser didSchemaParser) { this.didSchemaParser = didSchemaParser; } }
Fix botched conflict resolution
sli/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/normalization/did/DeterministicIdResolver.java
Fix botched conflict resolution
<ide><path>li/ingestion/ingestion-core/src/main/java/org/slc/sli/ingestion/transformation/normalization/did/DeterministicIdResolver.java <ide> return didSchemaParser.getRefConfigs().get(refType); <ide> } <ide> <del><<<<<<< HEAD <ide> private void handleDeterministicIdForReference(Entity entity, DidRefSource didRefSource, String collectionName, <ide> String tenantId, boolean addContext) throws IdResolutionException { <del>======= <del> private void handleDeterministicIdForReference(Entity entity, DidRefSource didRefSource, <del> String tenantId) throws IdResolutionException { <del>>>>>>>> master <ide> <ide> String entityType = didRefSource.getEntityType(); <ide> String sourceRefPath = didRefSource.getSourceRefPath();
Java
apache-2.0
33310f8c3c65e9c12ddf404d47c6de90213170c0
0
jimma/xerces,RackerWilliams/xercesj,ronsigal/xerces,ronsigal/xerces,jimma/xerces,ronsigal/xerces,RackerWilliams/xercesj,RackerWilliams/xercesj,jimma/xerces
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.util; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; /** * The XMLAttributesImpl class is an implementation of the XMLAttributes * interface which defines a collection of attributes for an element. * In the parser, the document source would scan the entire start element * and collect the attributes. The attributes are communicated to the * document handler in the startElement method. * <p> * The attributes are read-write so that subsequent stages in the document * pipeline can modify the values or change the attributes that are * propogated to the next stage. * * @see org.apache.xerces.xni.XMLDocumentHandler#startElement * * @author Andy Clark, IBM * @author Elena Litani, IBM * @author Michael Glavassevich, IBM * * @version $Id$ */ public class XMLAttributesImpl implements XMLAttributes { // // Constants // /** Default table size. */ protected static final int TABLE_SIZE = 101; /** * Threshold at which an instance is treated * as a large attribute list. */ protected static final int SIZE_LIMIT = 20; // // Data // // features /** Namespaces. */ protected boolean fNamespaces = true; // data /** * Usage count for the attribute table view. * Incremented each time all attributes are removed * when the attribute table view is in use. */ protected int fLargeCount = 1; /** Attribute count. */ protected int fLength; /** Attribute information. */ protected Attribute[] fAttributes = new Attribute[4]; /** * Hashtable of attribute information. * Provides an alternate view of the attribute specification. */ protected Attribute[] fAttributeTableView; /** * Tracks whether each chain in the hash table is stale * with respect to the current state of this object. * A chain is stale if its state is not the same as the number * of times the attribute table view has been used. */ protected int[] fAttributeTableViewChainState; /** * Actual number of buckets in the table view. */ protected int fTableViewBuckets; /** * Indicates whether the table view contains consistent data. */ protected boolean fIsTableViewConsistent; // // Constructors // /** Default constructor. */ public XMLAttributesImpl() { this(TABLE_SIZE); } /** * @param tableSize initial size of table view */ public XMLAttributesImpl(int tableSize) { fTableViewBuckets = tableSize; for (int i = 0; i < fAttributes.length; i++) { fAttributes[i] = new Attribute(); } } // <init>() // // Public methods // /** * Sets whether namespace processing is being performed. This state * is needed to return the correct value from the getLocalName method. * * @param namespaces True if namespace processing is turned on. * * @see #getLocalName */ public void setNamespaces(boolean namespaces) { fNamespaces = namespaces; } // setNamespaces(boolean) // // XMLAttributes methods // /** * Adds an attribute. The attribute's non-normalized value of the * attribute will have the same value as the attribute value until * set using the <code>setNonNormalizedValue</code> method. Also, * the added attribute will be marked as specified in the XML instance * document unless set otherwise using the <code>setSpecified</code> * method. * <p> * <strong>Note:</strong> If an attribute of the same name already * exists, the old values for the attribute are replaced by the new * values. * * @param name The attribute name. * @param type The attribute type. The type name is determined by * the type specified for this attribute in the DTD. * For example: "CDATA", "ID", "NMTOKEN", etc. However, * attributes of type enumeration will have the type * value specified as the pipe ('|') separated list of * the enumeration values prefixed by an open * parenthesis and suffixed by a close parenthesis. * For example: "(true|false)". * @param value The attribute value. * * @return Returns the attribute index. * * @see #setNonNormalizedValue * @see #setSpecified */ public int addAttribute(QName name, String type, String value) { int index; if (fLength < SIZE_LIMIT) { index = name.uri != null && !name.uri.equals("") ? getIndexFast(name.uri, name.localpart) : getIndexFast(name.rawname); if (index == -1) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length + 4]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } } } else if (name.uri == null || name.uri.length() == 0 || (index = getIndexFast(name.uri, name.localpart)) == -1) { /** * If attributes were removed from the list after the table * becomes in use this isn't reflected in the table view. It's * assumed that once a user starts removing attributes they're * not likely to add more. We only make the view consistent if * the user of this class adds attributes, removes them, and * then adds more. */ if (!fIsTableViewConsistent || fLength == SIZE_LIMIT) { prepareAndPopulateTableView(); fIsTableViewConsistent = true; } int bucket = getTableViewBucket(name.rawname); // The chain is stale. // This must be a unique attribute. if (fAttributeTableViewChainState[bucket] != fLargeCount) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length << 1]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // Update table view. fAttributeTableViewChainState[bucket] = fLargeCount; fAttributes[index].next = null; fAttributeTableView[bucket] = fAttributes[index]; } // This chain is active. // We need to check if any of the attributes has the same rawname. else { // Search the table. Attribute found = fAttributeTableView[bucket]; while (found != null) { if (found.name.rawname == name.rawname) { break; } found = found.next; } // This attribute is unique. if (found == null) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length << 1]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // Update table view fAttributes[index].next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = fAttributes[index]; } // Duplicate. We still need to find the index. else { index = getIndexFast(name.rawname); } } } // set values Attribute attribute = fAttributes[index]; attribute.name.setValues(name); attribute.type = type; attribute.value = value; attribute.nonNormalizedValue = value; attribute.specified = false; // clear augmentations attribute.augs.removeAllItems(); return index; } // addAttribute(QName,String,XMLString) /** * Removes all of the attributes. This method will also remove all * entities associated to the attributes. */ public void removeAllAttributes() { fLength = 0; } // removeAllAttributes() /** * Removes the attribute at the specified index. * <p> * <strong>Note:</strong> This operation changes the indexes of all * attributes following the attribute at the specified index. * * @param attrIndex The attribute index. */ public void removeAttributeAt(int attrIndex) { fIsTableViewConsistent = false; if (attrIndex < fLength - 1) { Attribute removedAttr = fAttributes[attrIndex]; System.arraycopy(fAttributes, attrIndex + 1, fAttributes, attrIndex, fLength - attrIndex - 1); // Make the discarded Attribute object available for re-use // by tucking it after the Attributes that are still in use fAttributes[fLength-1] = removedAttr; } fLength--; } // removeAttributeAt(int) /** * Sets the name of the attribute at the specified index. * * @param attrIndex The attribute index. * @param attrName The new attribute name. */ public void setName(int attrIndex, QName attrName) { fAttributes[attrIndex].name.setValues(attrName); } // setName(int,QName) /** * Sets the fields in the given QName structure with the values * of the attribute name at the specified index. * * @param attrIndex The attribute index. * @param attrName The attribute name structure to fill in. */ public void getName(int attrIndex, QName attrName) { attrName.setValues(fAttributes[attrIndex].name); } // getName(int,QName) /** * Sets the type of the attribute at the specified index. * * @param attrIndex The attribute index. * @param attrType The attribute type. The type name is determined by * the type specified for this attribute in the DTD. * For example: "CDATA", "ID", "NMTOKEN", etc. However, * attributes of type enumeration will have the type * value specified as the pipe ('|') separated list of * the enumeration values prefixed by an open * parenthesis and suffixed by a close parenthesis. * For example: "(true|false)". */ public void setType(int attrIndex, String attrType) { fAttributes[attrIndex].type = attrType; } // setType(int,String) /** * Sets the value of the attribute at the specified index. This * method will overwrite the non-normalized value of the attribute. * * @param attrIndex The attribute index. * @param attrValue The new attribute value. * * @see #setNonNormalizedValue */ public void setValue(int attrIndex, String attrValue) { Attribute attribute = fAttributes[attrIndex]; attribute.value = attrValue; attribute.nonNormalizedValue = attrValue; } // setValue(int,String) /** * Sets the non-normalized value of the attribute at the specified * index. * * @param attrIndex The attribute index. * @param attrValue The new non-normalized attribute value. */ public void setNonNormalizedValue(int attrIndex, String attrValue) { if (attrValue == null) { attrValue = fAttributes[attrIndex].value; } fAttributes[attrIndex].nonNormalizedValue = attrValue; } // setNonNormalizedValue(int,String) /** * Returns the non-normalized value of the attribute at the specified * index. If no non-normalized value is set, this method will return * the same value as the <code>getValue(int)</code> method. * * @param attrIndex The attribute index. */ public String getNonNormalizedValue(int attrIndex) { String value = fAttributes[attrIndex].nonNormalizedValue; return value; } // getNonNormalizedValue(int):String /** * Sets whether an attribute is specified in the instance document * or not. * * @param attrIndex The attribute index. * @param specified True if the attribute is specified in the instance * document. */ public void setSpecified(int attrIndex, boolean specified) { fAttributes[attrIndex].specified = specified; } // setSpecified(int,boolean) /** * Returns true if the attribute is specified in the instance document. * * @param attrIndex The attribute index. */ public boolean isSpecified(int attrIndex) { return fAttributes[attrIndex].specified; } // isSpecified(int):boolean // // AttributeList and Attributes methods // /** * Return the number of attributes in the list. * * <p>Once you know the number of attributes, you can iterate * through the list.</p> * * @return The number of attributes in the list. */ public int getLength() { return fLength; } // getLength():int /** * Look up an attribute's type by index. * * <p>The attribute type is one of the strings "CDATA", "ID", * "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", * or "NOTATION" (always in upper case).</p> * * <p>If the parser has not read a declaration for the attribute, * or if the parser does not report attribute types, then it must * return the value "CDATA" as stated in the XML 1.0 Recommentation * (clause 3.3.3, "Attribute-Value Normalization").</p> * * <p>For an enumerated attribute that is not a notation, the * parser will report the type as "NMTOKEN".</p> * * @param index The attribute index (zero-based). * @return The attribute's type as a string, or null if the * index is out of range. * @see #getLength */ public String getType(int index) { if (index < 0 || index >= fLength) { return null; } return getReportableType(fAttributes[index].type); } // getType(int):String /** * Look up an attribute's type by XML 1.0 qualified name. * * <p>See {@link #getType(int) getType(int)} for a description * of the possible types.</p> * * @param qname The XML 1.0 qualified name. * @return The attribute type as a string, or null if the * attribute is not in the list or if qualified names * are not available. */ public String getType(String qname) { int index = getIndex(qname); return index != -1 ? getReportableType(fAttributes[index].type) : null; } // getType(String):String /** * Look up an attribute's value by index. * * <p>If the attribute value is a list of tokens (IDREFS, * ENTITIES, or NMTOKENS), the tokens will be concatenated * into a single string with each token separated by a * single space.</p> * * @param index The attribute index (zero-based). * @return The attribute's value as a string, or null if the * index is out of range. * @see #getLength */ public String getValue(int index) { if (index < 0 || index >= fLength) { return null; } return fAttributes[index].value; } // getValue(int):String /** * Look up an attribute's value by XML 1.0 qualified name. * * <p>See {@link #getValue(int) getValue(int)} for a description * of the possible values.</p> * * @param qname The XML 1.0 qualified name. * @return The attribute value as a string, or null if the * attribute is not in the list or if qualified names * are not available. */ public String getValue(String qname) { int index = getIndex(qname); return index != -1 ? fAttributes[index].value : null; } // getValue(String):String // // AttributeList methods // /** * Return the name of an attribute in this list (by position). * * <p>The names must be unique: the SAX parser shall not include the * same attribute twice. Attributes without values (those declared * #IMPLIED without a value specified in the start tag) will be * omitted from the list.</p> * * <p>If the attribute name has a namespace prefix, the prefix * will still be attached.</p> * * @param i The index of the attribute in the list (starting at 0). * @return The name of the indexed attribute, or null * if the index is out of range. * @see #getLength */ public String getName(int index) { if (index < 0 || index >= fLength) { return null; } return fAttributes[index].name.rawname; } // getName(int):String // // Attributes methods // /** * Look up the index of an attribute by XML 1.0 qualified name. * * @param qName The qualified (prefixed) name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndex(String qName) { for (int i = 0; i < fLength; i++) { Attribute attribute = fAttributes[i]; if (attribute.name.rawname != null && attribute.name.rawname.equals(qName)) { return i; } } return -1; } // getIndex(String):int /** * Look up the index of an attribute by Namespace name. * * @param uri The Namespace URI, or null if * the name has no Namespace URI. * @param localName The attribute's local name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndex(String uri, String localPart) { for (int i = 0; i < fLength; i++) { Attribute attribute = fAttributes[i]; if (attribute.name.localpart != null && attribute.name.localpart.equals(localPart) && ((uri==attribute.name.uri) || (uri!=null && attribute.name.uri!=null && attribute.name.uri.equals(uri)))) { return i; } } return -1; } // getIndex(String,String):int /** * Look up an attribute's local name by index. * * @param index The attribute index (zero-based). * @return The local name, or the empty string if Namespace * processing is not being performed, or null * if the index is out of range. * @see #getLength */ public String getLocalName(int index) { if (!fNamespaces) { return ""; } if (index < 0 || index >= fLength) { return null; } return fAttributes[index].name.localpart; } // getLocalName(int):String /** * Look up an attribute's XML 1.0 qualified name by index. * * @param index The attribute index (zero-based). * @return The XML 1.0 qualified name, or the empty string * if none is available, or null if the index * is out of range. * @see #getLength */ public String getQName(int index) { if (index < 0 || index >= fLength) { return null; } String rawname = fAttributes[index].name.rawname; return rawname != null ? rawname : ""; } // getQName(int):String /** * Look up an attribute's type by Namespace name. * * <p>See {@link #getType(int) getType(int)} for a description * of the possible types.</p> * * @param uri The Namespace URI, or null if the * name has no Namespace URI. * @param localName The local name of the attribute. * @return The attribute type as a string, or null if the * attribute is not in the list or if Namespace * processing is not being performed. */ public String getType(String uri, String localName) { if (!fNamespaces) { return null; } int index = getIndex(uri, localName); return index != -1 ? getReportableType(fAttributes[index].type) : null; } // getType(String,String):String /** * Returns the prefix of the attribute at the specified index. * * @param index The index of the attribute. */ public String getPrefix(int index) { if (index < 0 || index >= fLength) { return null; } String prefix = fAttributes[index].name.prefix; // REVISIT: The empty string is not entered in the symbol table! return prefix != null ? prefix : ""; } // getPrefix(int):String /** * Look up an attribute's Namespace URI by index. * * @param index The attribute index (zero-based). * @return The Namespace URI * @see #getLength */ public String getURI(int index) { if (index < 0 || index >= fLength) { return null; } String uri = fAttributes[index].name.uri; return uri; } // getURI(int):String /** * Look up an attribute's value by Namespace name. * * <p>See {@link #getValue(int) getValue(int)} for a description * of the possible values.</p> * * @param uri The Namespace URI, or null if the * @param localName The local name of the attribute. * @return The attribute value as a string, or null if the * attribute is not in the list. */ public String getValue(String uri, String localName) { int index = getIndex(uri, localName); return index != -1 ? getValue(index) : null; } // getValue(String,String):String /** * Look up an augmentations by Namespace name. * * @param uri The Namespace URI, or null if the * @param localName The local name of the attribute. * @return Augmentations */ public Augmentations getAugmentations (String uri, String localName) { int index = getIndex(uri, localName); return index != -1 ? fAttributes[index].augs : null; } /** * Look up an augmentation by XML 1.0 qualified name. * <p> * * @param qName The XML 1.0 qualified name. * * @return Augmentations * */ public Augmentations getAugmentations(String qName){ int index = getIndex(qName); return index != -1 ? fAttributes[index].augs : null; } /** * Look up an augmentations by attributes index. * * @param attributeIndex The attribute index. * @return Augmentations */ public Augmentations getAugmentations (int attributeIndex){ if (attributeIndex < 0 || attributeIndex >= fLength) { return null; } return fAttributes[attributeIndex].augs; } /** * Sets the augmentations of the attribute at the specified index. * * @param attrIndex The attribute index. * @param augs The augmentations. */ public void setAugmentations(int attrIndex, Augmentations augs) { fAttributes[attrIndex].augs = augs; } /** * Sets the uri of the attribute at the specified index. * * @param attrIndex The attribute index. * @param uri Namespace uri */ public void setURI(int attrIndex, String uri) { fAttributes[attrIndex].name.uri = uri; } // getURI(int,QName) // Implementation methods public void setSchemaId(int attrIndex, boolean schemaId) { fAttributes[attrIndex].schemaId = schemaId; } public boolean getSchemaId(int index) { if (index < 0 || index >= fLength) { return false; } return fAttributes[index].schemaId; } public boolean getSchemaId(String qname) { int index = getIndex(qname); return index != -1 ? fAttributes[index].schemaId : false; } // getType(String):String public boolean getSchemaId(String uri, String localName) { if (!fNamespaces) { return false; } int index = getIndex(uri, localName); return index != -1 ? fAttributes[index].schemaId : false; } // getType(String,String):String /** * Look up the index of an attribute by XML 1.0 qualified name. * <p> * <strong>Note:</strong> * This method uses reference comparison, and thus should * only be used internally. We cannot use this method in any * code exposed to users as they may not pass in unique strings. * * @param qName The qualified (prefixed) name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndexFast(String qName) { for (int i = 0; i < fLength; ++i) { Attribute attribute = fAttributes[i]; if (attribute.name.rawname == qName) { return i; } } return -1; } // getIndexFast(String):int /** * Adds an attribute. The attribute's non-normalized value of the * attribute will have the same value as the attribute value until * set using the <code>setNonNormalizedValue</code> method. Also, * the added attribute will be marked as specified in the XML instance * document unless set otherwise using the <code>setSpecified</code> * method. * <p> * This method differs from <code>addAttribute</code> in that it * does not check if an attribute of the same name already exists * in the list before adding it. In order to improve performance * of namespace processing, this method allows uniqueness checks * to be deferred until all the namespace information is available * after the entire attribute specification has been read. * <p> * <strong>Caution:</strong> If this method is called it should * not be mixed with calls to <code>addAttribute</code> unless * it has been determined that all the attribute names are unique. * * @param name the attribute name * @param type the attribute type * @param value the attribute value * * @see #setNonNormalizedValue * @see #setSpecified * @see #checkDuplicatesNS */ public void addAttributeNS(QName name, String type, String value) { int index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes; if (fLength < SIZE_LIMIT) { attributes = new Attribute[fAttributes.length + 4]; } else { attributes = new Attribute[fAttributes.length << 1]; } System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // set values Attribute attribute = fAttributes[index]; attribute.name.setValues(name); attribute.type = type; attribute.value = value; attribute.nonNormalizedValue = value; attribute.specified = false; // clear augmentations attribute.augs.removeAllItems(); } /** * Checks for duplicate expanded names (local part and namespace name * pairs) in the attribute specification. If a duplicate is found its * name is returned. * <p> * This should be called once all the in-scope namespaces for the element * enclosing these attributes is known, and after all the attributes * have gone through namespace binding. * * @return the name of a duplicate attribute found in the search, * otherwise null. */ public QName checkDuplicatesNS() { // If the list is small check for duplicates using pairwise comparison. if (fLength <= SIZE_LIMIT) { for (int i = 0; i < fLength - 1; ++i) { Attribute att1 = fAttributes[i]; for (int j = i + 1; j < fLength; ++j) { Attribute att2 = fAttributes[j]; if (att1.name.localpart == att2.name.localpart && att1.name.uri == att2.name.uri) { return att2.name; } } } } // If the list is large check duplicates using a hash table. else { // We don't want this table view to be read if someone calls // addAttribute so we invalidate it up front. fIsTableViewConsistent = false; prepareTableView(); Attribute attr; int bucket; for (int i = fLength - 1; i >= 0; --i) { attr = fAttributes[i]; bucket = getTableViewBucket(attr.name.localpart, attr.name.uri); // The chain is stale. // This must be a unique attribute. if (fAttributeTableViewChainState[bucket] != fLargeCount) { fAttributeTableViewChainState[bucket] = fLargeCount; attr.next = null; fAttributeTableView[bucket] = attr; } // This chain is active. // We need to check if any of the attributes has the same name. else { // Search the table. Attribute found = fAttributeTableView[bucket]; while (found != null) { if (found.name.localpart == attr.name.localpart && found.name.uri == attr.name.uri) { return attr.name; } found = found.next; } // Update table view attr.next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = attr; } } } return null; } /** * Look up the index of an attribute by Namespace name. * <p> * <strong>Note:</strong> * This method uses reference comparison, and thus should * only be used internally. We cannot use this method in any * code exposed to users as they may not pass in unique strings. * * @param uri The Namespace URI, or null if * the name has no Namespace URI. * @param localName The attribute's local name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndexFast(String uri, String localPart) { for (int i = 0; i < fLength; ++i) { Attribute attribute = fAttributes[i]; if (attribute.name.localpart == localPart && attribute.name.uri == uri) { return i; } } return -1; } // getIndexFast(String,String):int /** * Returns the value passed in or NMTOKEN if it's an enumerated type. * * @param type attribute type * @return the value passed in or NMTOKEN if it's an enumerated type. */ private String getReportableType(String type) { if (type.charAt(0) == '(') { return "NMTOKEN"; } return type; } /** * Returns the position in the table view * where the given attribute name would be hashed. * * @param qname the attribute name * @return the position in the table view where the given attribute * would be hashed */ protected int getTableViewBucket(String qname) { return (qname.hashCode() & 0x7FFFFFFF) % fTableViewBuckets; } /** * Returns the position in the table view * where the given attribute name would be hashed. * * @param localpart the local part of the attribute * @param uri the namespace name of the attribute * @return the position in the table view where the given attribute * would be hashed */ protected int getTableViewBucket(String localpart, String uri) { if (uri == null) { return (localpart.hashCode() & 0x7FFFFFFF) % fTableViewBuckets; } else { return ((localpart.hashCode() + uri.hashCode()) & 0x7FFFFFFF) % fTableViewBuckets; } } /** * Purges all elements from the table view. */ protected void cleanTableView() { if (++fLargeCount < 0) { // Overflow. We actually need to visit the chain state array. if (fAttributeTableViewChainState != null) { for (int i = fTableViewBuckets - 1; i >= 0; --i) { fAttributeTableViewChainState[i] = 0; } } fLargeCount = 1; } } /** * Prepares the table view of the attributes list for use. */ protected void prepareTableView() { if (fAttributeTableView == null) { fAttributeTableView = new Attribute[fTableViewBuckets]; fAttributeTableViewChainState = new int[fTableViewBuckets]; } else { cleanTableView(); } } /** * Prepares the table view of the attributes list for use, * and populates it with the attributes which have been * previously read. */ protected void prepareAndPopulateTableView() { prepareTableView(); // Need to populate the hash table with the attributes we've scanned so far. Attribute attr; int bucket; for (int i = 0; i < fLength; ++i) { attr = fAttributes[i]; bucket = getTableViewBucket(attr.name.rawname); if (fAttributeTableViewChainState[bucket] != fLargeCount) { fAttributeTableViewChainState[bucket] = fLargeCount; attr.next = null; fAttributeTableView[bucket] = attr; } else { // Update table view attr.next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = attr; } } } // // Classes // /** * Attribute information. * * @author Andy Clark, IBM */ static class Attribute { // // Data // // basic info /** Name. */ public QName name = new QName(); /** Type. */ public String type; /** Value. */ public String value; /** Non-normalized value. */ public String nonNormalizedValue; /** Specified. */ public boolean specified; /** Schema ID type. */ public boolean schemaId; /** * Augmentations information for this attribute. * XMLAttributes has no knowledge if any augmentations * were attached to Augmentations. */ public Augmentations augs = new AugmentationsImpl(); // Additional data for attribute table view /** Pointer to the next attribute in the chain. **/ public Attribute next; } // class Attribute } // class XMLAttributesImpl
src/org/apache/xerces/util/XMLAttributesImpl.java
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xerces.util; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; /** * The XMLAttributesImpl class is an implementation of the XMLAttributes * interface which defines a collection of attributes for an element. * In the parser, the document source would scan the entire start element * and collect the attributes. The attributes are communicated to the * document handler in the startElement method. * <p> * The attributes are read-write so that subsequent stages in the document * pipeline can modify the values or change the attributes that are * propogated to the next stage. * * @see org.apache.xerces.xni.XMLDocumentHandler#startElement * * @author Andy Clark, IBM * @author Elena Litani, IBM * @author Michael Glavassevich, IBM * * @version $Id$ */ public class XMLAttributesImpl implements XMLAttributes { // // Constants // /** Default table size. */ protected static final int TABLE_SIZE = 101; /** * Threshold at which an instance is treated * as a large attribute list. */ protected static final int SIZE_LIMIT = 20; // // Data // // features /** Namespaces. */ protected boolean fNamespaces = true; // data /** * Usage count for the attribute table view. * Incremented each time all attributes are removed * when the attribute table view is in use. */ protected int fLargeCount = 1; /** Attribute count. */ protected int fLength; /** Attribute information. */ protected Attribute[] fAttributes = new Attribute[4]; /** * Hashtable of attribute information. * Provides an alternate view of the attribute specification. */ protected Attribute[] fAttributeTableView; /** * Tracks whether each chain in the hash table is stale * with respect to the current state of this object. * A chain is stale if its state is not the same as the number * of times the attribute table view has been used. */ protected int[] fAttributeTableViewChainState; /** * Actual number of buckets in the table view. */ protected int fTableViewBuckets; /** * Indicates whether the table view contains consistent data. */ protected boolean fIsTableViewConsistent; // // Constructors // /** Default constructor. */ public XMLAttributesImpl() { this(TABLE_SIZE); } /** * @param tableSize initial size of table view */ public XMLAttributesImpl(int tableSize) { fTableViewBuckets = tableSize; for (int i = 0; i < fAttributes.length; i++) { fAttributes[i] = new Attribute(); } } // <init>() // // Public methods // /** * Sets whether namespace processing is being performed. This state * is needed to return the correct value from the getLocalName method. * * @param namespaces True if namespace processing is turned on. * * @see #getLocalName */ public void setNamespaces(boolean namespaces) { fNamespaces = namespaces; } // setNamespaces(boolean) // // XMLAttributes methods // /** * Adds an attribute. The attribute's non-normalized value of the * attribute will have the same value as the attribute value until * set using the <code>setNonNormalizedValue</code> method. Also, * the added attribute will be marked as specified in the XML instance * document unless set otherwise using the <code>setSpecified</code> * method. * <p> * <strong>Note:</strong> If an attribute of the same name already * exists, the old values for the attribute are replaced by the new * values. * * @param name The attribute name. * @param type The attribute type. The type name is determined by * the type specified for this attribute in the DTD. * For example: "CDATA", "ID", "NMTOKEN", etc. However, * attributes of type enumeration will have the type * value specified as the pipe ('|') separated list of * the enumeration values prefixed by an open * parenthesis and suffixed by a close parenthesis. * For example: "(true|false)". * @param value The attribute value. * * @return Returns the attribute index. * * @see #setNonNormalizedValue * @see #setSpecified */ public int addAttribute(QName name, String type, String value) { int index; if (fLength < SIZE_LIMIT) { index = name.uri != null && !name.uri.equals("") ? getIndexFast(name.uri, name.localpart) : getIndexFast(name.rawname); if (index == -1) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length + 4]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } } } else if (name.uri == null || name.uri.length() == 0 || (index = getIndexFast(name.uri, name.localpart)) == -1) { /** * If attributes were removed from the list after the table * becomes in use this isn't reflected in the table view. It's * assumed that once a user starts removing attributes they're * not likely to add more. We only make the view consistent if * the user of this class adds attributes, removes them, and * then adds more. */ if (!fIsTableViewConsistent || fLength == SIZE_LIMIT) { prepareAndPopulateTableView(); fIsTableViewConsistent = true; } int bucket = getTableViewBucket(name.rawname); // The chain is stale. // This must be a unique attribute. if (fAttributeTableViewChainState[bucket] != fLargeCount) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length << 1]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // Update table view. fAttributeTableViewChainState[bucket] = fLargeCount; fAttributes[index].next = null; fAttributeTableView[bucket] = fAttributes[index]; } // This chain is active. // We need to check if any of the attributes has the same rawname. else { // Search the table. Attribute found = fAttributeTableView[bucket]; while (found != null) { if (found.name.rawname == name.rawname) { break; } found = found.next; } // This attribute is unique. if (found == null) { index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes = new Attribute[fAttributes.length << 1]; System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // Update table view fAttributes[index].next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = fAttributes[index]; } // Duplicate. We still need to find the index. else { index = getIndexFast(name.rawname); } } } // set values Attribute attribute = fAttributes[index]; attribute.name.setValues(name); attribute.type = type; attribute.value = value; attribute.nonNormalizedValue = value; attribute.specified = false; // clear augmentations attribute.augs.removeAllItems(); return index; } // addAttribute(QName,String,XMLString) /** * Removes all of the attributes. This method will also remove all * entities associated to the attributes. */ public void removeAllAttributes() { fLength = 0; } // removeAllAttributes() /** * Removes the attribute at the specified index. * <p> * <strong>Note:</strong> This operation changes the indexes of all * attributes following the attribute at the specified index. * * @param attrIndex The attribute index. */ public void removeAttributeAt(int attrIndex) { fIsTableViewConsistent = false; if (attrIndex < fLength - 1) { Attribute removedAttr = fAttributes[attrIndex]; System.arraycopy(fAttributes, attrIndex + 1, fAttributes, attrIndex, fLength - attrIndex - 1); // Make the discarded Attribute object available for re-use // by tucking it after the Attributes that are still in use fAttributes[fLength-1] = removedAttr; } fLength--; } // removeAttributeAt(int) /** * Sets the name of the attribute at the specified index. * * @param attrIndex The attribute index. * @param attrName The new attribute name. */ public void setName(int attrIndex, QName attrName) { fAttributes[attrIndex].name.setValues(attrName); } // setName(int,QName) /** * Sets the fields in the given QName structure with the values * of the attribute name at the specified index. * * @param attrIndex The attribute index. * @param attrName The attribute name structure to fill in. */ public void getName(int attrIndex, QName attrName) { attrName.setValues(fAttributes[attrIndex].name); } // getName(int,QName) /** * Sets the type of the attribute at the specified index. * * @param attrIndex The attribute index. * @param attrType The attribute type. The type name is determined by * the type specified for this attribute in the DTD. * For example: "CDATA", "ID", "NMTOKEN", etc. However, * attributes of type enumeration will have the type * value specified as the pipe ('|') separated list of * the enumeration values prefixed by an open * parenthesis and suffixed by a close parenthesis. * For example: "(true|false)". */ public void setType(int attrIndex, String attrType) { fAttributes[attrIndex].type = attrType; } // setType(int,String) /** * Sets the value of the attribute at the specified index. This * method will overwrite the non-normalized value of the attribute. * * @param attrIndex The attribute index. * @param attrValue The new attribute value. * * @see #setNonNormalizedValue */ public void setValue(int attrIndex, String attrValue) { Attribute attribute = fAttributes[attrIndex]; attribute.value = attrValue; attribute.nonNormalizedValue = attrValue; } // setValue(int,String) /** * Sets the non-normalized value of the attribute at the specified * index. * * @param attrIndex The attribute index. * @param attrValue The new non-normalized attribute value. */ public void setNonNormalizedValue(int attrIndex, String attrValue) { if (attrValue == null) { attrValue = fAttributes[attrIndex].value; } fAttributes[attrIndex].nonNormalizedValue = attrValue; } // setNonNormalizedValue(int,String) /** * Returns the non-normalized value of the attribute at the specified * index. If no non-normalized value is set, this method will return * the same value as the <code>getValue(int)</code> method. * * @param attrIndex The attribute index. */ public String getNonNormalizedValue(int attrIndex) { String value = fAttributes[attrIndex].nonNormalizedValue; return value; } // getNonNormalizedValue(int):String /** * Sets whether an attribute is specified in the instance document * or not. * * @param attrIndex The attribute index. * @param specified True if the attribute is specified in the instance * document. */ public void setSpecified(int attrIndex, boolean specified) { fAttributes[attrIndex].specified = specified; } // setSpecified(int,boolean) /** * Returns true if the attribute is specified in the instance document. * * @param attrIndex The attribute index. */ public boolean isSpecified(int attrIndex) { return fAttributes[attrIndex].specified; } // isSpecified(int):boolean // // AttributeList and Attributes methods // /** * Return the number of attributes in the list. * * <p>Once you know the number of attributes, you can iterate * through the list.</p> * * @return The number of attributes in the list. */ public int getLength() { return fLength; } // getLength():int /** * Look up an attribute's type by index. * * <p>The attribute type is one of the strings "CDATA", "ID", * "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", "ENTITIES", * or "NOTATION" (always in upper case).</p> * * <p>If the parser has not read a declaration for the attribute, * or if the parser does not report attribute types, then it must * return the value "CDATA" as stated in the XML 1.0 Recommentation * (clause 3.3.3, "Attribute-Value Normalization").</p> * * <p>For an enumerated attribute that is not a notation, the * parser will report the type as "NMTOKEN".</p> * * @param index The attribute index (zero-based). * @return The attribute's type as a string, or null if the * index is out of range. * @see #getLength */ public String getType(int index) { if (index < 0 || index >= fLength) { return null; } return getReportableType(fAttributes[index].type); } // getType(int):String /** * Look up an attribute's type by XML 1.0 qualified name. * * <p>See {@link #getType(int) getType(int)} for a description * of the possible types.</p> * * @param qname The XML 1.0 qualified name. * @return The attribute type as a string, or null if the * attribute is not in the list or if qualified names * are not available. */ public String getType(String qname) { int index = getIndex(qname); return index != -1 ? getReportableType(fAttributes[index].type) : null; } // getType(String):String /** * Look up an attribute's value by index. * * <p>If the attribute value is a list of tokens (IDREFS, * ENTITIES, or NMTOKENS), the tokens will be concatenated * into a single string with each token separated by a * single space.</p> * * @param index The attribute index (zero-based). * @return The attribute's value as a string, or null if the * index is out of range. * @see #getLength */ public String getValue(int index) { if (index < 0 || index >= fLength) { return null; } return fAttributes[index].value; } // getValue(int):String /** * Look up an attribute's value by XML 1.0 qualified name. * * <p>See {@link #getValue(int) getValue(int)} for a description * of the possible values.</p> * * @param qname The XML 1.0 qualified name. * @return The attribute value as a string, or null if the * attribute is not in the list or if qualified names * are not available. */ public String getValue(String qname) { int index = getIndex(qname); return index != -1 ? fAttributes[index].value : null; } // getValue(String):String // // AttributeList methods // /** * Return the name of an attribute in this list (by position). * * <p>The names must be unique: the SAX parser shall not include the * same attribute twice. Attributes without values (those declared * #IMPLIED without a value specified in the start tag) will be * omitted from the list.</p> * * <p>If the attribute name has a namespace prefix, the prefix * will still be attached.</p> * * @param i The index of the attribute in the list (starting at 0). * @return The name of the indexed attribute, or null * if the index is out of range. * @see #getLength */ public String getName(int index) { if (index < 0 || index >= fLength) { return null; } return fAttributes[index].name.rawname; } // getName(int):String // // Attributes methods // /** * Look up the index of an attribute by XML 1.0 qualified name. * * @param qName The qualified (prefixed) name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndex(String qName) { for (int i = 0; i < fLength; i++) { Attribute attribute = fAttributes[i]; if (attribute.name.rawname != null && attribute.name.rawname.equals(qName)) { return i; } } return -1; } // getIndex(String):int /** * Look up the index of an attribute by Namespace name. * * @param uri The Namespace URI, or null if * the name has no Namespace URI. * @param localName The attribute's local name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndex(String uri, String localPart) { for (int i = 0; i < fLength; i++) { Attribute attribute = fAttributes[i]; if (attribute.name.localpart != null && attribute.name.localpart.equals(localPart) && ((uri==attribute.name.uri) || (uri!=null && attribute.name.uri!=null && attribute.name.uri.equals(uri)))) { return i; } } return -1; } // getIndex(String,String):int /** * Look up an attribute's local name by index. * * @param index The attribute index (zero-based). * @return The local name, or the empty string if Namespace * processing is not being performed, or null * if the index is out of range. * @see #getLength */ public String getLocalName(int index) { if (!fNamespaces) { return ""; } if (index < 0 || index >= fLength) { return null; } return fAttributes[index].name.localpart; } // getLocalName(int):String /** * Look up an attribute's XML 1.0 qualified name by index. * * @param index The attribute index (zero-based). * @return The XML 1.0 qualified name, or the empty string * if none is available, or null if the index * is out of range. * @see #getLength */ public String getQName(int index) { if (index < 0 || index >= fLength) { return null; } String rawname = fAttributes[index].name.rawname; return rawname != null ? rawname : ""; } // getQName(int):String /** * Look up an attribute's type by Namespace name. * * <p>See {@link #getType(int) getType(int)} for a description * of the possible types.</p> * * @param uri The Namespace URI, or null if the * name has no Namespace URI. * @param localName The local name of the attribute. * @return The attribute type as a string, or null if the * attribute is not in the list or if Namespace * processing is not being performed. */ public String getType(String uri, String localName) { if (!fNamespaces) { return null; } int index = getIndex(uri, localName); return index != -1 ? getReportableType(fAttributes[index].type) : null; } // getType(String,String):String /** * Returns the prefix of the attribute at the specified index. * * @param index The index of the attribute. */ public String getPrefix(int index) { if (index < 0 || index >= fLength) { return null; } String prefix = fAttributes[index].name.prefix; // REVISIT: The empty string is not entered in the symbol table! return prefix != null ? prefix : ""; } // getPrefix(int):String /** * Look up an attribute's Namespace URI by index. * * @param index The attribute index (zero-based). * @return The Namespace URI * @see #getLength */ public String getURI(int index) { if (index < 0 || index >= fLength) { return null; } String uri = fAttributes[index].name.uri; return uri; } // getURI(int):String /** * Look up an attribute's value by Namespace name. * * <p>See {@link #getValue(int) getValue(int)} for a description * of the possible values.</p> * * @param uri The Namespace URI, or null if the * @param localName The local name of the attribute. * @return The attribute value as a string, or null if the * attribute is not in the list. */ public String getValue(String uri, String localName) { int index = getIndex(uri, localName); return index != -1 ? getValue(index) : null; } // getValue(String,String):String /** * Look up an augmentations by Namespace name. * * @param uri The Namespace URI, or null if the * @param localName The local name of the attribute. * @return Augmentations */ public Augmentations getAugmentations (String uri, String localName) { int index = getIndex(uri, localName); return index != -1 ? fAttributes[index].augs : null; } /** * Look up an augmentation by XML 1.0 qualified name. * <p> * * @param qName The XML 1.0 qualified name. * * @return Augmentations * */ public Augmentations getAugmentations(String qName){ int index = getIndex(qName); return index != -1 ? fAttributes[index].augs : null; } /** * Look up an augmentations by attributes index. * * @param attributeIndex The attribute index. * @return Augmentations */ public Augmentations getAugmentations (int attributeIndex){ if (attributeIndex < 0 || attributeIndex >= fLength) { return null; } return fAttributes[attributeIndex].augs; } /** * Sets the augmentations of the attribute at the specified index. * * @param attrIndex The attribute index. * @param augs The augmentations. */ public void setAugmentations(int attrIndex, Augmentations augs) { fAttributes[attrIndex].augs = augs; } /** * Sets the uri of the attribute at the specified index. * * @param attrIndex The attribute index. * @param uri Namespace uri */ public void setURI(int attrIndex, String uri) { fAttributes[attrIndex].name.uri = uri; } // getURI(int,QName) // Implementation methods public void setSchemaId(int attrIndex, boolean schemaId) { fAttributes[attrIndex].schemaId = schemaId; } public boolean getSchemaId(int index) { if (index < 0 || index >= fLength) { return false; } return fAttributes[index].schemaId; } public boolean getSchemaId(String qname) { int index = getIndex(qname); return index != -1 ? fAttributes[index].schemaId : false; } // getType(String):String public boolean getSchemaId(String uri, String localName) { if (!fNamespaces) { return false; } int index = getIndex(uri, localName); return index != -1 ? fAttributes[index].schemaId : false; } // getType(String,String):String /** * Look up the index of an attribute by XML 1.0 qualified name. * <p> * <strong>Note:</strong> * This method uses reference comparison, and thus should * only be used internally. We cannot use this method in any * code exposed to users as they may not pass in unique strings. * * @param qName The qualified (prefixed) name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndexFast(String qName) { for (int i = 0; i < fLength; ++i) { Attribute attribute = fAttributes[i]; if (attribute.name.rawname == qName) { return i; } } return -1; } // getIndexFast(String):int /** * Adds an attribute. The attribute's non-normalized value of the * attribute will have the same value as the attribute value until * set using the <code>setNonNormalizedValue</code> method. Also, * the added attribute will be marked as specified in the XML instance * document unless set otherwise using the <code>setSpecified</code> * method. * <p> * This method differs from <code>addAttribute</code> in that it * does not check if an attribute of the same name already exists * in the list before adding it. In order to improve performance * of namespace processing, this method allows uniqueness checks * to be deferred until all the namespace information is available * after the entire attribute specification has been read. * <p> * <strong>Caution:</strong> If this method is called it should * not be mixed with calls to <code>addAttribute</code> unless * it has been determined that all the attribute names are unique. * * @param name the attribute name * @param type the attribute type * @param value the attribute value * * @see #setNonNormalizedValue * @see #setSpecified * @see #checkDuplicatesNS */ public void addAttributeNS(QName name, String type, String value) { int index = fLength; if (fLength++ == fAttributes.length) { Attribute[] attributes; if (fLength < SIZE_LIMIT) { attributes = new Attribute[fAttributes.length + 4]; } else { attributes = new Attribute[fAttributes.length << 1]; } System.arraycopy(fAttributes, 0, attributes, 0, fAttributes.length); for (int i = fAttributes.length; i < attributes.length; i++) { attributes[i] = new Attribute(); } fAttributes = attributes; } // set values Attribute attribute = fAttributes[index]; attribute.name.setValues(name); attribute.type = type; attribute.value = value; attribute.nonNormalizedValue = value; attribute.specified = false; // clear augmentations attribute.augs.removeAllItems(); } /** * Checks for duplicate expanded names (local part and namespace name * pairs) in the attribute specification. If a duplicate is found its * name is returned. * <p> * This should be called once all the in-scope namespaces for the element * enclosing these attributes is known, and after all the attributes * have gone through namespace binding. * * @return the name of a duplicate attribute found in the search, * otherwise null. */ public QName checkDuplicatesNS() { // If the list is small check for duplicates using pairwise comparison. if (fLength <= SIZE_LIMIT) { for (int i = 0; i < fLength - 1; ++i) { Attribute att1 = fAttributes[i]; for (int j = i + 1; j < fLength; ++j) { Attribute att2 = fAttributes[j]; if (att1.name.localpart == att2.name.localpart && att1.name.uri == att2.name.uri) { return att2.name; } } } } // If the list is large check duplicates using a hash table. else { // We don't want this table view to be read if someone calls // addAttribute so we invalidate it up front. fIsTableViewConsistent = false; prepareTableView(); Attribute attr; int bucket; for (int i = fLength - 1; i >= 0; --i) { attr = fAttributes[i]; bucket = getTableViewBucket(attr.name.localpart, attr.name.uri); // The chain is stale. // This must be a unique attribute. if (fAttributeTableViewChainState[bucket] != fLargeCount) { fAttributeTableViewChainState[bucket] = fLargeCount; attr.next = null; fAttributeTableView[bucket] = attr; } // This chain is active. // We need to check if any of the attributes has the same name. else { // Search the table. Attribute found = fAttributeTableView[bucket]; while (found != null) { if (found.name.localpart == attr.name.localpart && found.name.uri == attr.name.uri) { return attr.name; } found = found.next; } // Update table view attr.next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = attr; } } } return null; } /** * Look up the index of an attribute by Namespace name. * <p> * <strong>Note:</strong> * This method uses reference comparison, and thus should * only be used internally. We cannot use this method in any * code exposed to users as they may not pass in unique strings. * * @param uri The Namespace URI, or null if * the name has no Namespace URI. * @param localName The attribute's local name. * @return The index of the attribute, or -1 if it does not * appear in the list. */ public int getIndexFast(String uri, String localPart) { for (int i = 0; i < fLength; ++i) { Attribute attribute = fAttributes[i]; if (attribute.name.localpart == localPart && attribute.name.uri == uri) { return i; } } return -1; } // getIndexFast(String,String):int /** * Returns the value passed in or NMTOKEN if it's an enumerated type. * * @param type attribute type * @return the value passed in or NMTOKEN if it's an enumerated type. */ protected String getReportableType(String type) { if (type.indexOf('(') == 0 && type.lastIndexOf(')') == type.length()-1) { return "NMTOKEN"; } return type; } /** * Returns the position in the table view * where the given attribute name would be hashed. * * @param qname the attribute name * @return the position in the table view where the given attribute * would be hashed */ protected int getTableViewBucket(String qname) { return (qname.hashCode() & 0x7FFFFFFF) % fTableViewBuckets; } /** * Returns the position in the table view * where the given attribute name would be hashed. * * @param localpart the local part of the attribute * @param uri the namespace name of the attribute * @return the position in the table view where the given attribute * would be hashed */ protected int getTableViewBucket(String localpart, String uri) { if (uri == null) { return (localpart.hashCode() & 0x7FFFFFFF) % fTableViewBuckets; } else { return ((localpart.hashCode() + uri.hashCode()) & 0x7FFFFFFF) % fTableViewBuckets; } } /** * Purges all elements from the table view. */ protected void cleanTableView() { if (++fLargeCount < 0) { // Overflow. We actually need to visit the chain state array. if (fAttributeTableViewChainState != null) { for (int i = fTableViewBuckets - 1; i >= 0; --i) { fAttributeTableViewChainState[i] = 0; } } fLargeCount = 1; } } /** * Prepares the table view of the attributes list for use. */ protected void prepareTableView() { if (fAttributeTableView == null) { fAttributeTableView = new Attribute[fTableViewBuckets]; fAttributeTableViewChainState = new int[fTableViewBuckets]; } else { cleanTableView(); } } /** * Prepares the table view of the attributes list for use, * and populates it with the attributes which have been * previously read. */ protected void prepareAndPopulateTableView() { prepareTableView(); // Need to populate the hash table with the attributes we've scanned so far. Attribute attr; int bucket; for (int i = 0; i < fLength; ++i) { attr = fAttributes[i]; bucket = getTableViewBucket(attr.name.rawname); if (fAttributeTableViewChainState[bucket] != fLargeCount) { fAttributeTableViewChainState[bucket] = fLargeCount; attr.next = null; fAttributeTableView[bucket] = attr; } else { // Update table view attr.next = fAttributeTableView[bucket]; fAttributeTableView[bucket] = attr; } } } // // Classes // /** * Attribute information. * * @author Andy Clark, IBM */ static class Attribute { // // Data // // basic info /** Name. */ public QName name = new QName(); /** Type. */ public String type; /** Value. */ public String value; /** Non-normalized value. */ public String nonNormalizedValue; /** Specified. */ public boolean specified; /** Schema ID type. */ public boolean schemaId; /** * Augmentations information for this attribute. * XMLAttributes has no knowledge if any augmentations * were attached to Augmentations. */ public Augmentations augs = new AugmentationsImpl(); // Additional data for attribute table view /** Pointer to the next attribute in the chain. **/ public Attribute next; } // class Attribute } // class XMLAttributesImpl
Improve performance of getType. To determine if we're looking at an enumerated type it is sufficient to check that the first char is a '('. If it is a '(' then it cannot be anything else. git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@319661 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/xerces/util/XMLAttributesImpl.java
Improve performance of getType. To determine if we're looking at an enumerated type it is sufficient to check that the first char is a '('. If it is a '(' then it cannot be anything else.
<ide><path>rc/org/apache/xerces/util/XMLAttributesImpl.java <ide> * @param type attribute type <ide> * @return the value passed in or NMTOKEN if it's an enumerated type. <ide> */ <del> protected String getReportableType(String type) { <del> <del> if (type.indexOf('(') == 0 && type.lastIndexOf(')') == type.length()-1) { <add> private String getReportableType(String type) { <add> <add> if (type.charAt(0) == '(') { <ide> return "NMTOKEN"; <ide> } <ide> return type;
Java
apache-2.0
a6ab5ef940c8ceb4e9c7158a790ad81fc82dd68b
0
orekyuu/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,semonte/intellij-community,retomerz/intellij-community,holmes/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,adedayo/intellij-community,fnouama/intellij-community,kool79/intellij-community,fitermay/intellij-community,supersven/intellij-community,semonte/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,caot/intellij-community,blademainer/intellij-community,izonder/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,ryano144/intellij-community,caot/intellij-community,xfournet/intellij-community,fitermay/intellij-community,xfournet/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,clumsy/intellij-community,diorcety/intellij-community,clumsy/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,samthor/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,nicolargo/intellij-community,da1z/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,jagguli/intellij-community,holmes/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,samthor/intellij-community,suncycheng/intellij-community,izonder/intellij-community,slisson/intellij-community,ryano144/intellij-community,ibinti/intellij-community,dslomov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,allotria/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,signed/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,orekyuu/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,wreckJ/intellij-community,kool79/intellij-community,signed/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,fitermay/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,allotria/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ibinti/intellij-community,holmes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,samthor/intellij-community,xfournet/intellij-community,da1z/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,retomerz/intellij-community,amith01994/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,allotria/intellij-community,blademainer/intellij-community,apixandru/intellij-community,semonte/intellij-community,robovm/robovm-studio,ibinti/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,vladmm/intellij-community,apixandru/intellij-community,hurricup/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,robovm/robovm-studio,hurricup/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,supersven/intellij-community,diorcety/intellij-community,kdwink/intellij-community,semonte/intellij-community,fnouama/intellij-community,diorcety/intellij-community,kdwink/intellij-community,blademainer/intellij-community,dslomov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,blademainer/intellij-community,slisson/intellij-community,amith01994/intellij-community,ryano144/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,caot/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,nicolargo/intellij-community,supersven/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,gnuhub/intellij-community,da1z/intellij-community,clumsy/intellij-community,signed/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,supersven/intellij-community,dslomov/intellij-community,holmes/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,jagguli/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,amith01994/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,semonte/intellij-community,asedunov/intellij-community,fitermay/intellij-community,dslomov/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,semonte/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ryano144/intellij-community,holmes/intellij-community,petteyg/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,slisson/intellij-community,hurricup/intellij-community,caot/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,vladmm/intellij-community,ryano144/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,signed/intellij-community,petteyg/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,hurricup/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,vladmm/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,robovm/robovm-studio,kool79/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,dslomov/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,allotria/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,signed/intellij-community,da1z/intellij-community,slisson/intellij-community,youdonghai/intellij-community,supersven/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,diorcety/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,apixandru/intellij-community,amith01994/intellij-community,adedayo/intellij-community,caot/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,asedunov/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,FHannes/intellij-community,asedunov/intellij-community,kool79/intellij-community,signed/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,fengbaicanhe/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,da1z/intellij-community,clumsy/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,clumsy/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,samthor/intellij-community,kool79/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,supersven/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,caot/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,fitermay/intellij-community,FHannes/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,ryano144/intellij-community,slisson/intellij-community,orekyuu/intellij-community,da1z/intellij-community,dslomov/intellij-community,amith01994/intellij-community,samthor/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,kool79/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,izonder/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ryano144/intellij-community,da1z/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,caot/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,samthor/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,caot/intellij-community,fitermay/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,semonte/intellij-community,jagguli/intellij-community,jagguli/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,adedayo/intellij-community,fnouama/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,izonder/intellij-community,blademainer/intellij-community,caot/intellij-community,xfournet/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,signed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,da1z/intellij-community,izonder/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,signed/intellij-community,petteyg/intellij-community,amith01994/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,holmes/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,retomerz/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,caot/intellij-community,semonte/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,fitermay/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,hurricup/intellij-community,kdwink/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,amith01994/intellij-community,slisson/intellij-community,da1z/intellij-community,xfournet/intellij-community,slisson/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community
package com.jetbrains.python.psi.search; import com.intellij.openapi.project.Project; import com.intellij.psi.search.ProjectScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.util.Processor; import com.intellij.util.QueryExecutor; import com.intellij.util.containers.HashSet; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.stubs.PySuperClassIndex; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author yole */ public class PyClassInheritorsSearchExecutor implements QueryExecutor<PyClass, PyClassInheritorsSearch.SearchParameters> { /** * These base classes are to general to look for inheritors list. */ protected static final List<String> IGNORED_BASES = new ArrayList<String>(3); static { IGNORED_BASES.add("object"); IGNORED_BASES.add("BaseException"); IGNORED_BASES.add("Exception"); } public boolean execute(final PyClassInheritorsSearch.SearchParameters queryParameters, final Processor<PyClass> consumer) { Set<PyClass> processed = new HashSet<PyClass>(); return processDirectInheritors(queryParameters.getSuperClass(), consumer, queryParameters.isCheckDeepInheritance(), processed); } private static boolean processDirectInheritors( final PyClass superClass, final Processor<PyClass> consumer, final boolean checkDeep, final Set<PyClass> processed ) { for (String ig_base : IGNORED_BASES) { if (ig_base.equals(superClass.getName())) return true; // we don't want to look for inheritors of overly general classes } if (processed.contains(superClass)) return true; processed.add(superClass); Project project = superClass.getProject(); final String superClassName = superClass.getName(); if (superClassName == null) return true; final Collection<PyClass> candidates = StubIndex.getInstance().get(PySuperClassIndex.KEY, superClassName, project, ProjectScope.getAllScope(project)); for(PyClass candidate: candidates) { final PyClass[] classes = candidate.getSuperClasses(); for(PyClass superClassCandidate: classes) { if (superClassCandidate.isEquivalentTo(superClass)) { if (!consumer.process(candidate)) { return false; } if (checkDeep && !processDirectInheritors(candidate, consumer, checkDeep, processed)) return false; break; } } } return true; } }
python/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java
package com.jetbrains.python.psi.search; import com.intellij.openapi.project.Project; import com.intellij.psi.search.ProjectScope; import com.intellij.psi.stubs.StubIndex; import com.intellij.util.Processor; import com.intellij.util.QueryExecutor; import com.intellij.util.containers.HashSet; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.stubs.PySuperClassIndex; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author yole */ public class PyClassInheritorsSearchExecutor implements QueryExecutor<PyClass, PyClassInheritorsSearch.SearchParameters> { /** * These base classes are to general to look for inheritors list. */ protected static final List<String> IGNORED_BASES = new ArrayList<String>(3); static { IGNORED_BASES.add("object"); IGNORED_BASES.add("BaseException"); IGNORED_BASES.add("Exception"); } public boolean execute(final PyClassInheritorsSearch.SearchParameters queryParameters, final Processor<PyClass> consumer) { Set<PyClass> processed = new HashSet<PyClass>(); return processDirectInheritors(queryParameters.getSuperClass(), consumer, queryParameters.isCheckDeepInheritance(), processed); } private static boolean processDirectInheritors( final PyClass superClass, final Processor<PyClass> consumer, final boolean checkDeep, final Set<PyClass> processed ) { for (String ig_base : IGNORED_BASES) { if (ig_base.equals(superClass.getName())) return true; // we don't want to look for inheritors of overly general classes } if (processed.contains(superClass)) return true; processed.add(superClass); Project project = superClass.getProject(); final String superClassName = superClass.getName(); if (superClassName == null) return true; final Collection<PyClass> candidates = StubIndex.getInstance().get(PySuperClassIndex.KEY, superClassName, project, ProjectScope.getAllScope(project)); for(PyClass candidate: candidates) { final PyClass[] classes = candidate.getSuperClasses(); if (classes != null) { for(PyClass superClassCandidate: classes) { if (superClassCandidate.isEquivalentTo(superClass)) { if (!consumer.process(candidate)) { return false; } if (checkDeep && !processDirectInheritors(candidate, consumer, checkDeep, processed)) return false; break; } } } } return true; } }
cleanup
python/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java
cleanup
<ide><path>ython/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java <ide> ProjectScope.getAllScope(project)); <ide> for(PyClass candidate: candidates) { <ide> final PyClass[] classes = candidate.getSuperClasses(); <del> if (classes != null) { <del> for(PyClass superClassCandidate: classes) { <del> if (superClassCandidate.isEquivalentTo(superClass)) { <del> if (!consumer.process(candidate)) { <del> return false; <del> } <del> if (checkDeep && !processDirectInheritors(candidate, consumer, checkDeep, processed)) return false; <del> break; <add> for(PyClass superClassCandidate: classes) { <add> if (superClassCandidate.isEquivalentTo(superClass)) { <add> if (!consumer.process(candidate)) { <add> return false; <ide> } <add> if (checkDeep && !processDirectInheritors(candidate, consumer, checkDeep, processed)) return false; <add> break; <ide> } <ide> } <ide> }
Java
apache-2.0
ae07e95bba7bbf245121eefcd809634a8e0c8757
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/** * 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.geronimo.console.databasemanager.wizard; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.SortedSet; import javax.enterprise.deploy.model.DDBean; import javax.enterprise.deploy.model.DDBeanRoot; import javax.enterprise.deploy.shared.ModuleType; import javax.enterprise.deploy.spi.DeploymentConfiguration; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.TargetModuleID; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.portlet.PortletFileUpload; import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance; import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager; import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot; import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB; import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter; import org.apache.geronimo.connector.deployment.jsr88.SinglePool; import org.apache.geronimo.connector.outbound.PoolingAttributes; import org.apache.geronimo.console.BasePortlet; import org.apache.geronimo.console.ajax.ProgressInfo; import org.apache.geronimo.console.databasemanager.ManagementHelper; import org.apache.geronimo.console.util.PortletManager; import org.apache.geronimo.converter.DatabaseConversionStatus; import org.apache.geronimo.converter.JDBCPool; import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter; import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter; import org.apache.geronimo.deployment.service.jsr88.EnvironmentData; import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable; import org.apache.geronimo.gbean.AbstractName; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.GBeanNotFoundException; import org.apache.geronimo.kernel.InternalKernelException; import org.apache.geronimo.kernel.KernelRegistry; import org.apache.geronimo.kernel.config.ConfigurationManager; import org.apache.geronimo.kernel.config.ConfigurationUtil; import org.apache.geronimo.kernel.management.State; import org.apache.geronimo.kernel.proxy.GeronimoManagedBean; import org.apache.geronimo.kernel.repository.Artifact; import org.apache.geronimo.kernel.repository.FileWriteMonitor; import org.apache.geronimo.kernel.repository.ListableRepository; import org.apache.geronimo.kernel.repository.WriteableRepository; import org.apache.geronimo.kernel.util.XmlUtil; import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory; import org.apache.geronimo.management.geronimo.ResourceAdapterModule; import org.apache.geronimo.system.plugin.PluginInstallerGBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * A portlet that lets you configure and deploy JDBC connection pools. * * @version $Rev$ $Date$ */ public class DatabasePoolPortlet extends BasePortlet { private static final Logger log = LoggerFactory.getLogger(DatabasePoolPortlet.class); private final static Set<String> INCLUDE_ARTIFACTIDS = new HashSet<String>(Arrays.asList("system-database")); private final static Set<String> EXCLUDE_GROUPIDS = new HashSet<String>(Arrays.asList("org.apache.geronimo.modules", "org.apache.geronimo.configs", "org.apache.geronimo.applications", "org.apache.geronimo.assemblies", "org.apache.cxf", "org.apache.tomcat", "org.tranql", "commons-cli", "commons-io", "commons-logging", "commons-lang", "axis", "org.apache.axis2", "org.apache.directory", "org.apache.activemq", "org.apache.openejb", "org.apache.myfaces", "org.mortbay.jetty")); private final static String DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers"; private final static String CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam"; private final static String DRIVER_INFO_URL = "http://geronimo.apache.org/driver-downloads.properties"; private static final String LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp"; private static final String EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp"; private static final String SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp"; private static final String BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp"; private static final String CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp"; private static final String TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp"; private static final String DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp"; private static final String DOWNLOAD_STATUS_VIEW = "/WEB-INF/view/dbwizard/downloadStatus.jsp"; private static final String SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp"; private static final String IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp"; private static final String IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp"; private static final String USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp"; private static final String LIST_MODE = "list"; private static final String EDIT_MODE = "edit"; private static final String SELECT_RDBMS_MODE = "rdbms"; private static final String BASIC_PARAMS_MODE = "params"; private static final String CONFIRM_URL_MODE = "url"; private static final String TEST_CONNECTION_MODE = "test"; private static final String SHOW_PLAN_MODE = "plan"; private static final String DOWNLOAD_MODE = "download"; private static final String DOWNLOAD_STATUS_MODE = "downloadStatus"; private static final String EDIT_EXISTING_MODE = "editExisting"; private static final String DELETE_MODE = "delete"; private static final String SAVE_MODE = "save"; private static final String IMPORT_START_MODE = "startImport"; private static final String IMPORT_UPLOAD_MODE = "importUpload"; private static final String IMPORT_STATUS_MODE = "importStatus"; private static final String IMPORT_COMPLETE_MODE = "importComplete"; private static final String WEBLOGIC_IMPORT_MODE = "weblogicImport"; private static final String USAGE_MODE = "usage"; private static final String IMPORT_EDIT_MODE = "importEdit"; private static final String MODE_KEY = "mode"; private static final String LOCAL = "LOCAL"; private static final String XA = "XA"; private static final String NONE = "NONE"; private static final String[] ORDERED_PROPERTY_NAMES = { "property-DatabaseName", "property-CreateDatabase", "property-UserName", "property-Password" }; private PortletRequestDispatcher listView; private PortletRequestDispatcher editView; private PortletRequestDispatcher selectRDBMSView; private PortletRequestDispatcher basicParamsView; private PortletRequestDispatcher confirmURLView; private PortletRequestDispatcher testConnectionView; private PortletRequestDispatcher downloadView; private PortletRequestDispatcher downloadStatusView; private PortletRequestDispatcher planView; private PortletRequestDispatcher importUploadView; private PortletRequestDispatcher importStatusView; private PortletRequestDispatcher usageView; private Map<String, String> rarPathMap; public void init(PortletConfig portletConfig) throws PortletException { super.init(portletConfig); listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW); editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW); selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW); basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW); confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW); testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW); downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW); downloadStatusView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_STATUS_VIEW); planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW); importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW); importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW); usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW); rarPathMap = new HashMap<String, String>(); rarPathMap.put("TranQL XA Resource Adapter for DB2", "tranql-connector-db2-xa"); rarPathMap.put("TranQL Client Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-client-local"); rarPathMap.put("TranQL Client XA Resource Adapter for Apache Derby", "tranql-connector-derby-client-xa"); rarPathMap.put("TranQL Embedded Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-xa"); // rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); rarPathMap.put("TranQL XA Resource Adapter for Informix", "tranql-connector-informix-xa"); rarPathMap.put("TranQL Client Local Transaction Resource Adapter for MySQL", "tranql-connector-mysql-local"); rarPathMap.put("TranQL Client XA Resource Adapter for MySQL", "tranql-connector-mysql-xa"); rarPathMap.put("TranQL Local Resource Adapter for Oracle", "tranql-connector-oracle-local"); rarPathMap.put("TranQL XA Resource Adapter for Oracle", "tranql-connector-oracle-xa"); rarPathMap.put("TranQL Local Resource Adapter for PostgreSQL", "tranql-connector-postgresql-local"); rarPathMap.put("TranQL XA Resource Adapter for PostgreSQL", "tranql-connector-postgresql-xa"); rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2000", "tranql-connector-sqlserver2000-xa"); rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2005", "tranql-connector-sqlserver2005-xa"); } public void destroy() { listView = null; editView = null; selectRDBMSView = null; basicParamsView = null; confirmURLView = null; testConnectionView = null; downloadView = null; downloadStatusView = null; planView = null; importUploadView = null; importStatusView = null; usageView = null; rarPathMap.clear(); super.destroy(); } public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) { PortletSession session = request.getPortletSession(true); DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if (results == null || results.length ==0) { DriverDownloader downloader = new DriverDownloader(); try { results = downloader.loadDriverInfo(new URL(DRIVER_INFO_URL)); session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE); } catch (MalformedURLException e) { log.error("Unable to download driver data", e); results = new DriverDownloader.DriverInfo[0]; } } return results; } /** * Loads data about a resource adapter. Depending on what we already have, may load * the name and description, but always loads the config property descriptions. * * @param request Pass it or die * @param rarPath If we're creating a new RA, the path to identify it * @param displayName If we're editing an existing RA, its name * @param adapterAbstractName If we're editing an existing RA, its AbstractName * @return resource adapter parameter data object */ public ResourceAdapterParams getRARConfiguration(PortletRequest request, String rarPath, String displayName, String adapterAbstractName) { PortletSession session = request.getPortletSession(true); if (rarPath != null && !rarPath.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute( CONFIG_SESSION_KEY + "-" + rarPath, PortletSession.APPLICATION_SCOPE); if (results == null) { results = loadConfigPropertiesByPath(request, rarPath); session.setAttribute(CONFIG_SESSION_KEY + "-" + rarPath, results, PortletSession.APPLICATION_SCOPE); session.setAttribute(CONFIG_SESSION_KEY + "-" + results.displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else if (displayName != null && !displayName.equals( "") && adapterAbstractName != null && !adapterAbstractName.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute( CONFIG_SESSION_KEY + "-" + displayName, PortletSession.APPLICATION_SCOPE); if (results == null) { results = loadConfigPropertiesByAbstractName(request, rarPathMap.get(displayName), adapterAbstractName); session.setAttribute(CONFIG_SESSION_KEY + "-" + displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else { throw new IllegalArgumentException(); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter(MODE_KEY); if (mode.equals(IMPORT_UPLOAD_MODE)) { processImportUpload(actionRequest, actionResponse); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); return; } PoolData data = new PoolData(); data.load(actionRequest); if (mode.equals("process-" + SELECT_RDBMS_MODE)) { DatabaseDriver info = getDatabaseInfo(actionRequest, data); if (info != null) { data.rarPath = info.getRAR().toString(); if (info.isSpecific()) { data.adapterDisplayName = "Unknown"; // will pick these up when we process the RA type in the render request data.adapterDescription = "Unknown"; actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { data.driverClass = info.getDriverClassName(); data.urlPrototype = info.getURLPrototype(); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else { actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE); } } else if (mode.equals("process-" + DOWNLOAD_MODE)) { String name = actionRequest.getParameter("driverName"); DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest); DriverDownloader.DriverInfo found = null; for (DriverDownloader.DriverInfo driver : drivers) { if (driver.getName().equals(name)) { found = driver; break; } } if (found != null) { data.jars = new String[]{found.getRepositoryURI()}; try { PluginInstallerGBean installer = KernelRegistry.getSingleKernel().getGBean(PluginInstallerGBean.class); //WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0]; final PortletSession session = actionRequest.getPortletSession(); ProgressInfo progressInfo = new ProgressInfo(); progressInfo.setMainMessage("Downloading " + found.getName()); session.setAttribute(ProgressInfo.PROGRESS_INFO_KEY, progressInfo, PortletSession.APPLICATION_SCOPE); // Start the download monitoring new Thread(new Downloader(found, progressInfo, installer)).start(); actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_STATUS_MODE); } catch (GBeanNotFoundException e) { throw new PortletException(e); } catch (InternalKernelException e) { throw new PortletException(e); } catch (IllegalStateException e) { throw new PortletException(e); } } else { actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_MODE); } } else if (mode.equals("process-" + DOWNLOAD_STATUS_MODE)) { if (data.getDbtype() == null || data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } else { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } } else if (mode.equals("process-" + BASIC_PARAMS_MODE)) { DatabaseDriver info; info = getDatabaseInfo(actionRequest, data); if (info != null) { data.url = populateURL(info.getURLPrototype(), info.getURLParameters(), data.getUrlProperties()); } if (attemptDriverLoad(actionRequest, data) != null) { actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE); } else { actionResponse.setRenderParameter("driverError", "Unable to load driver " + data.driverClass); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if (mode.equals("process-" + CONFIRM_URL_MODE)) { String test = actionRequest.getParameter("test"); if (test == null || test.equals("true")) { try { String targetDBInfo = attemptConnect(actionRequest, data); actionResponse.setRenderParameter("targetDBInfo", targetDBInfo); actionResponse.setRenderParameter("connected", "true"); } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter temp = new PrintWriter(writer); e.printStackTrace(temp); temp.flush(); temp.close(); addErrorMessage(actionRequest, getLocalizedString(actionRequest, "dbwizard.testConnection.connectionError"), writer.getBuffer().toString()); actionResponse.setRenderParameter("connected", "false"); } actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE); } else { save(actionRequest, actionResponse, data, false); } } else if (mode.equals(SAVE_MODE)) { save(actionRequest, actionResponse, data, false); } else if (mode.equals(SHOW_PLAN_MODE)) { String plan = save(actionRequest, actionResponse, data, true); actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan); actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE); } else if (mode.equals(EDIT_EXISTING_MODE)) { final String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); actionResponse.setRenderParameter("adapterAbstractName", name); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(SELECT_RDBMS_MODE)) { if (data.getAdapterDisplayName() == null) { // Set a default for a new pool data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; } actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(WEBLOGIC_IMPORT_MODE)) { String domainDir = actionRequest.getParameter("weblogicDomainDir"); String libDir = actionRequest.getParameter("weblogicLibDir"); try { DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir); actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } catch (Exception e) { log.error("Unable to import", e); actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE); } } else if (mode.equals(IMPORT_START_MODE)) { actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(IMPORT_EDIT_MODE)) { ImportStatus status = getImportStatus(actionRequest); int index = Integer.parseInt(actionRequest.getParameter("importIndex")); status.setCurrentPoolIndex(index); loadImportedData(actionRequest, data, status.getCurrentPool()); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(IMPORT_COMPLETE_MODE)) { ImportStatus status = getImportStatus(actionRequest); log.warn("Import Results:"); //todo: create a screen for this log.warn(" " + status.getSkippedCount() + " ignored"); log.warn(" " + status.getStartedCount() + " reviewed but not deployed"); log.warn(" " + status.getPendingCount() + " not reviewed"); log.warn(" " + status.getFinishedCount() + " deployed"); actionRequest.getPortletSession().removeAttribute("ImportStatus"); } else if (mode.equals(DELETE_MODE)) { String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); delete(actionRequest, actionResponse, data); } else { actionResponse.setRenderParameter(MODE_KEY, mode); } data.store(actionResponse); } private static class Downloader implements Runnable { private PluginInstallerGBean installer; private DriverDownloader.DriverInfo driver; private ProgressInfo progressInfo; public Downloader(DriverDownloader.DriverInfo driver, ProgressInfo progressInfo, PluginInstallerGBean installer) { this.driver = driver; this.progressInfo = progressInfo; this.installer = installer; } public void run() { DriverDownloader downloader = new DriverDownloader(); try { downloader.loadDriver(installer, driver, new FileWriteMonitor() { private int fileSize; public void writeStarted(String fileDescription, int fileSize) { this.fileSize = fileSize; log.info("Downloading " + fileDescription); } public void writeProgress(int bytes) { int kbDownloaded = (int) Math.floor(bytes / 1024); if (fileSize > 0) { int percent = (bytes * 100) / fileSize; progressInfo.setProgressPercent(percent); progressInfo.setSubMessage(kbDownloaded + " / " + fileSize / 1024 + " Kb downloaded"); } else { progressInfo.setSubMessage(kbDownloaded + " Kb downloaded"); } } public void writeComplete(int bytes) { log.info("Finished downloading " + bytes + " b"); } }); } catch (IOException e) { log.error("Unable to download database driver", e); } finally { progressInfo.setFinished(true); } } } private void loadImportedData(PortletRequest request, PoolData data, ImportStatus.PoolProgress progress) throws PortletException { if (!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) { JDBCPool pool = (JDBCPool) progress.getPool(); data.dbtype = "Other"; data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis()); data.driverClass = pool.getDriverClass(); data.idleTimeout = pool.getIdleTimeoutMillis() != null ? Integer.toString( pool.getIdleTimeoutMillis().intValue() / (60 * 1000)) : null; data.maxSize = getImportString(pool.getMaxSize()); data.minSize = getImportString(pool.getMinSize()); data.name = pool.getName(); data.password = pool.getPassword(); data.url = pool.getJdbcURL(); data.user = pool.getUsername(); if (pool.getDriverClass() != null) { DatabaseDriver info = getDatabaseInfoFromDriver(request, data); if (info != null) { data.rarPath = info.getRAR().toString(); data.urlPrototype = info.getURLPrototype(); } else { throw new PortletException("Don't recognize database driver " + data.driverClass + "!"); } } } else { //todo: handle XA } } private static String getImportString(Integer value) { return value == null ? null : value.toString(); } private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException { String type = request.getParameter("importSource"); response.setRenderParameter("importSource", type); if (!PortletFileUpload.isMultipartContent(request)) { throw new PortletException("Expected file upload"); } PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory()); try { List<FileItem> items = uploader.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = File.createTempFile("geronimo-import", ""); file.deleteOnExit(); log.debug("Writing database pool import file to " + file.getAbsolutePath()); item.write(file); DatabaseConversionStatus status = processImport(file, type); request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); return true; } else { throw new PortletException("Not expecting any form fields"); } } } catch (PortletException e) { throw e; } catch (Exception e) { throw new PortletException(e); } return false; } private DatabaseConversionStatus processImport(File importFile, String type) throws PortletException, IOException { if (type.equals("JBoss 4")) { return JBoss4DatabaseConverter.convert(new FileReader(importFile)); } else if (type.equals("WebLogic 8.1")) { return WebLogic81DatabaseConverter.convert(new FileReader(importFile)); } else { throw new PortletException("Unknown import type '" + type + "'"); } } private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String rarPath) { DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { //URI uri = getRAR(request, rarPath).toURI(); ConnectorDeployable deployable = new ConnectorDeployable(PortletManager.getRepositoryEntryBundle(request, rarPath)); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); String adapterName = null, adapterDesc = null; String[] test = ddBeanRoot.getText("connector/display-name"); if (test != null && test.length > 0) { adapterName = test[0]; } test = ddBeanRoot.getText("connector/description"); if (test != null && test.length > 0) { adapterDesc = test[0]; } DDBean[] definitions = ddBeanRoot.getChildBean( "connector/resourceadapter/outbound-resourceadapter/connection-definition"); List<ConfigParam> configs = new ArrayList<ConfigParam>(); if (definitions != null) { for (DDBean definition : definitions) { String iface = definition.getText("connectionfactory-interface")[0]; if (iface.equals("javax.sql.DataSource")) { DDBean[] beans = definition.getChildBean("config-property"); for (DDBean bean : beans) { String name = bean.getText("config-property-name")[0].trim(); String type = bean.getText("config-property-type")[0].trim(); test = bean.getText("config-property-value"); String value = test == null || test.length == 0 ? null : test[0].trim(); test = bean.getText("description"); String desc = test == null || test.length == 0 ? null : test[0].trim(); configs.add(new ConfigParam(name, type, desc, value)); } } } } return new ResourceAdapterParams(adapterName, adapterDesc, rarPath.substring(11, rarPath.length()-5), configs.toArray(new ConfigParam[configs.size()])); } catch (Exception e) { log.error("Unable to read configuration properties", e); return null; } finally { if (mgr != null) mgr.release(); } } private ResourceAdapterParams loadConfigPropertiesByAbstractName(PortletRequest request, String rarPath, String abstractName) { ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, new AbstractName(URI.create(abstractName))); String dd = module.getDeploymentDescriptor(); DocumentBuilderFactory factory = XmlUtil.newDocumentBuilderFactory(); factory.setValidating(false); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); final StringReader reader = new StringReader(dd); Document doc = builder.parse(new InputSource(reader)); reader.close(); Element elem = doc.getDocumentElement(); // connector String displayName = getFirstText(elem.getElementsByTagName("display-name")); String description = getFirstText(elem.getElementsByTagName("description")); elem = (Element) elem.getElementsByTagName("resourceadapter").item(0); elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0); NodeList defs = elem.getElementsByTagName("connection-definition"); List<ConfigParam> all = new ArrayList<ConfigParam>(); for (int i = 0; i < defs.getLength(); i++) { final Element def = (Element) defs.item(i); String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim(); if (iface.equals("javax.sql.DataSource")) { NodeList configs = def.getElementsByTagName("config-property"); for (int j = 0; j < configs.getLength(); j++) { Element config = (Element) configs.item(j); String name = getFirstText(config.getElementsByTagName("config-property-name")).trim(); String type = getFirstText(config.getElementsByTagName("config-property-type")).trim(); String test = getFirstText(config.getElementsByTagName("config-property-value")); String value = test == null ? null : test.trim(); test = getFirstText(config.getElementsByTagName("description")); String desc = test == null ? null : test.trim(); all.add(new ConfigParam(name, type, desc, value)); } } } return new ResourceAdapterParams(displayName, description, rarPath, all.toArray(new ConfigParam[all.size()])); } catch (Exception e) { log.error("Unable to read resource adapter DD", e); return null; } } private String getFirstText(NodeList list) { if (list.getLength() == 0) { return null; } Element first = (Element) list.item(0); StringBuilder buf = new StringBuilder(); NodeList all = first.getChildNodes(); for (int i = 0; i < all.getLength(); i++) { Node node = all.item(i); if (node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); } } return buf.toString(); } private void loadConnectionFactory(ActionRequest actionRequest, String adapterName, String factoryName, PoolData data) { AbstractName abstractAdapterName = new AbstractName(URI.create(adapterName)); AbstractName abstractFactoryName = new AbstractName(URI.create(factoryName)); ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest, abstractAdapterName); JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest, abstractFactoryName); data.adapterDisplayName = adapter.getDisplayName(); data.adapterDescription = adapter.getDescription(); try { data.name = (String) abstractFactoryName.getName().get("name"); if (data.isGeneric()) { data.url = (String) factory.getConfigProperty("ConnectionURL"); data.driverClass = (String) factory.getConfigProperty("Driver"); data.user = (String) factory.getConfigProperty("UserName"); data.password = (String) factory.getConfigProperty("Password"); } else { ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(), data.getAdapterDisplayName(), adapterName); for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam cp = params.getConfigParams()[i]; Object value = factory.getConfigProperty(cp.getName()); data.properties.put("property-" + cp.getName(), value == null ? null : value.toString()); } data.sort(); } } catch (Exception e) { log.error("Unable to look up connection property", e); } //todo: push the lookup into ManagementHelper /* PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer(); data.minSize = Integer.toString(pool.getPartitionMinSize()); data.maxSize = Integer.toString(pool.getPartitionMaxSize()); data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds()); data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes()); */ } protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { return; } try { String mode = renderRequest.getParameter(MODE_KEY); PoolData data = new PoolData(); data.load(renderRequest); renderRequest.setAttribute("pool", data); // If not headed anywhere in particular, send to list if (mode == null || mode.equals("")) { mode = LIST_MODE; } // If headed to list but there's an import in progress, redirect to import status if (mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) { mode = IMPORT_STATUS_MODE; } if (mode.equals(LIST_MODE)) { renderList(renderRequest, renderResponse); } else if (mode.equals(EDIT_MODE)) { renderEdit(renderRequest, renderResponse, data); } else if (mode.equals(SELECT_RDBMS_MODE)) { renderSelectRDBMS(renderRequest, renderResponse); } else if (mode.equals(DOWNLOAD_MODE)) { renderDownload(renderRequest, renderResponse); } else if (mode.equals(DOWNLOAD_STATUS_MODE)) { renderDownloadStatus(renderRequest, renderResponse); } else if (mode.equals(BASIC_PARAMS_MODE)) { renderBasicParams(renderRequest, renderResponse, data); } else if (mode.equals(CONFIRM_URL_MODE)) { renderConfirmURL(renderRequest, renderResponse); } else if (mode.equals(TEST_CONNECTION_MODE)) { renderTestConnection(renderRequest, renderResponse); } else if (mode.equals(SHOW_PLAN_MODE)) { renderPlan(renderRequest, renderResponse, data); } else if (mode.equals(IMPORT_START_MODE)) { renderImportUploadForm(renderRequest, renderResponse); } else if (mode.equals(IMPORT_STATUS_MODE)) { renderImportStatus(renderRequest, renderResponse); } else if (mode.equals(USAGE_MODE)) { renderUsage(renderRequest, renderResponse); } } catch (Throwable e) { log.error("Unable to render portlet", e); } } private void renderUsage(RenderRequest request, RenderResponse response) throws IOException, PortletException { usageView.include(request, response); } private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("status", getImportStatus(request)); populatePoolList(request); importStatusView.include(request, response); } private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("from", request.getParameter("from")); importUploadView.include(request, response); } private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { populatePoolList(renderRequest); listView.include(renderRequest, renderResponse); } private void populatePoolList(PortletRequest renderRequest) { ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource"); List<ConnectionPool> list = new ArrayList<ConnectionPool>(); for (ResourceAdapterModule module : modules) { AbstractName moduleName = PortletManager.getManagementHelper(renderRequest).getNameFor(module); JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module, "javax.sql.DataSource"); for (JCAManagedConnectionFactory db : databases) { AbstractName dbName = PortletManager.getManagementHelper(renderRequest).getNameFor(db); list.add(new ConnectionPool(moduleName, dbName, (String) dbName.getName().get(NameFactory.J2EE_NAME), PortletManager.getManagedBean(renderRequest, dbName).getState())); } } Collections.sort(list); renderRequest.setAttribute("pools", list); } private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { if (data.abstractName == null || data.abstractName.equals("")) { DatabaseDriver info = getDatabaseInfo(renderRequest, data); loadDriverJARList(renderRequest, info); } if (!data.isGeneric()) { ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(), data.getAdapterDisplayName(), renderRequest.getParameter("adapterAbstractName")); data.adapterDisplayName = params.getDisplayName(); data.adapterDescription = params.getDescription(); data.adapterRarPath = params.getRarPath(); Map<String, ConfigParam> map = new HashMap<String, ConfigParam>(); boolean more = false; for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam param = params.getConfigParams()[i]; if (!data.properties.containsKey("property-" + param.getName())) { data.properties.put("property-" + param.getName(), param.getDefaultValue()); more = true; } map.put("property-" + param.getName(), param); } if (more) { data.loadPropertyNames(); } data.sort(); renderRequest.setAttribute("ConfigParams", map); } editView.include(renderRequest, renderResponse); } private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("databases", getAllDrivers(renderRequest)); selectRDBMSView.include(renderRequest, renderResponse); } private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("drivers", getDriverInfo(renderRequest)); downloadView.include(renderRequest, renderResponse); } private void renderDownloadStatus(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { downloadStatusView.include(renderRequest, renderResponse); } private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { DatabaseDriver info = getDatabaseInfo(renderRequest, data); loadDriverJARList(renderRequest, info); // Make sure all properties available for the DB are listed if (info != null) { for (String param : info.getURLParameters()) { final String key = "urlproperty-" + param; if (!data.getUrlProperties().containsKey(key)) { data.getUrlProperties().put(key, param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? info.getDefaultPort() : null); } } } // Pass on errors renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError")); basicParamsView.include(renderRequest, renderResponse); } private void loadDriverJARList(RenderRequest renderRequest, DatabaseDriver info) { // List the available JARs List<String> list = new ArrayList<String>(); ListableRepository[] repos = PortletManager.getCurrentServer(renderRequest).getRepositories(); Set<Artifact> dependencyFilters = info == null? null : info.getDependencyFilters(); for (ListableRepository repo : repos) { SortedSet<Artifact> artifacts = repo.list(); for (Artifact artifact : artifacts) { if (dependencyFilters != null) { for (Artifact filter: dependencyFilters) { // It is too strict if using artifact.matches(filter) if (filter.getGroupId() != null && artifact.getGroupId().indexOf(filter.getGroupId()) == -1) continue; if (filter.getArtifactId() != null && artifact.getArtifactId().indexOf(filter.getArtifactId()) == -1) continue; if (filter.getVersion() != null && !artifact.getVersion().equals(filter.getVersion())) continue; if (filter.getType() != null && !artifact.getType().equals(filter.getType())) continue; list.add(artifact.toString()); } } else if (INCLUDE_ARTIFACTIDS.contains(artifact.getArtifactId()) || !EXCLUDE_GROUPIDS.contains(artifact.getGroupId())) { list.add(artifact.toString()); } } } Collections.sort(list); renderRequest.setAttribute("availableJars", list); } private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { confirmURLView.include(renderRequest, renderResponse); } private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("targetDBInfo", renderRequest.getParameter("targetDBInfo")); renderRequest.setAttribute("connected", Boolean.valueOf(renderRequest.getParameter("connected"))); testConnectionView.include(renderRequest, renderResponse); } private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan")); // Digest the RAR URI String path = PortletManager.getRepositoryEntry(renderRequest, data.getRarPath()).getPath(); String base = PortletManager.getCurrentServer(renderRequest).getServerInfo().getCurrentBaseDirectory(); if (base != null && path.startsWith(base)) { path = path.substring(base.length()); if (path.startsWith("/")) { path = path.substring(1); } } else { int pos = path.lastIndexOf('/'); path = path.substring(pos + 1); } renderRequest.setAttribute("rarRelativePath", path); planView.include(renderRequest, renderResponse); } private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException { Class driverClass = attemptDriverLoad(request, data); Driver driver = (Driver) driverClass.newInstance(); if (driver.acceptsURL(data.url)) { Properties props = new Properties(); if (data.user != null) { props.put("user", data.user); } if (data.password != null) { props.put("password", data.password); } Connection con = null; try { con = driver.connect(data.url, props); final DatabaseMetaData metaData = con.getMetaData(); return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion(); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { //ignore } } } } else throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url); } private void delete(PortletRequest request, ActionResponse response, PoolData data) { // check to make sure the abstract name does not begin with 'org.apache.geronimo.configs' // if it does not - then delete it -- otherwise it is a system database if (data.getAbstractName() != null) { boolean isSystemDatabasePool = (data.getAbstractName().indexOf("org.apache.geronimo.configs") == 0); if (!isSystemDatabasePool) { DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { // retrieve all running modules TargetModuleID[] runningIds = mgr.getRunningModules(ModuleType.RAR, mgr.getTargets()); // index of module to keep int index = -1; // only keep module id that is associated with selected DB pool for (int i = 0; i < runningIds.length; i++) { if (data.getAbstractName().contains(runningIds[i].getModuleID())) { index = i; break; } } TargetModuleID[] ids = {runningIds[index]}; // undeploy the db pool ProgressObject po = mgr.undeploy(ids); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { log.info("Undeployment completed successfully!"); } } catch (Exception e) { log.error("Undeployment unsuccessful!"); } finally { if (mgr != null) mgr.release(); } } } } private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) { ImportStatus status = getImportStatus(request); if (data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool data.name = data.name.replaceAll("\\s", ""); DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { String rarPath = data.getRarPath(); File rarFile = getRAR(request, rarPath); //URI uri = getRAR(request, data.getRarPath()).toURI(); ConnectorDeployable deployable = new ConnectorDeployable(PortletManager.getRepositoryEntryBundle(request, rarPath)); DeploymentConfiguration config = mgr.createConfiguration(deployable); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot); ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean( ddBeanRoot.getChildBean(root.getXpaths()[0])[0]); EnvironmentData environment = new EnvironmentData(); connector.setEnvironment(environment); org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact(); environment.setConfigId(configId); configId.setGroupId("console.dbpool"); configId.setVersion("1.0"); configId.setType("car"); String artifactId = data.name; // simply replace / with _ if / exists within the artifactId // this is needed because we don't allow / within the artifactId artifactId = artifactId.replace('/', '_'); // Let's check whether the artifact exists ConfigurationManager configurationManager = ConfigurationUtil.getConfigurationManager(PortletManager.getKernel()); if (configurationManager.isInstalled(new Artifact(configId.getGroupId(), artifactId, configId.getVersion(), configId.getType()))) { artifactId = artifactId + "_" + new Random(System.currentTimeMillis()).nextInt(99); } configId.setArtifactId(artifactId); String[] jars = data.getJars(); int length = jars[jars.length - 1].length() == 0 ? jars.length - 1 : jars.length; org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length]; for (int i = 0; i < dependencies.length; i++) { dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact(); } environment.setDependencies(dependencies); for (int i = 0; i < dependencies.length; i++) { Artifact tmp = Artifact.create(jars[i]); dependencies[i].setGroupId(tmp.getGroupId()); dependencies[i].setArtifactId(tmp.getArtifactId()); dependencies[i].setVersion(tmp.getVersion().toString()); dependencies[i].setType(tmp.getType()); } ResourceAdapter adapter = connector.getResourceAdapter()[0]; ConnectionDefinition definition = new ConnectionDefinition(); adapter.setConnectionDefinition(new ConnectionDefinition[]{definition}); definition.setConnectionFactoryInterface("javax.sql.DataSource"); ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance(); definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance}); instance.setName(data.getName()); ConfigPropertySetting[] settings = instance.getConfigPropertySetting(); if (data.isGeneric()) { // it's a generic TranQL JDBC pool for (ConfigPropertySetting setting : settings) { if (setting.getName().equals("UserName")) { setting.setValue(data.user); } else if (setting.getName().equals("Password")) { setting.setValue(data.password); } else if (setting.getName().equals("ConnectionURL")) { setting.setValue(data.url); } else if (setting.getName().equals("Driver")) { setting.setValue(data.driverClass); } } } else { // it's an XA driver or non-TranQL RA for (ConfigPropertySetting setting : settings) { String value = data.properties.get("property-" + setting.getName()); setting.setValue(value == null ? "" : value); } } ConnectionManager manager = instance.getConnectionManager(); if(XA.equals(data.transactionType)){ manager.setTransactionXA(true); } else if (NONE.equals(data.transactionType)){ manager.setTransactionNone(true); } else { manager.setTransactionLocal(true); } SinglePool pool = new SinglePool(); manager.setPoolSingle(pool); pool.setMatchOne(true); // Max Size needs to be set before the minimum. This is because // the connection manager will constrain the minimum based on the // current maximum value in the pool. We might consider adding a // setPoolConstraints method to allow specifying both at the same time. if (data.maxSize != null && !data.maxSize.equals("")) { pool.setMaxSize(new Integer(data.maxSize)); } if (data.minSize != null && !data.minSize.equals("")) { pool.setMinSize(new Integer(data.minSize)); } if (data.blockingTimeout != null && !data.blockingTimeout.equals("")) { pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout)); } if (data.idleTimeout != null && !data.idleTimeout.equals("")) { pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout)); } if (planOnly) { ByteArrayOutputStream out = new ByteArrayOutputStream(); config.save(out); out.close(); return new String(out.toByteArray(), "US-ASCII"); } else { File tempFile = File.createTempFile("console-deployment", ".xml"); tempFile.deleteOnExit(); log.debug("Writing database pool deployment plan to " + tempFile.getAbsolutePath()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); config.save(out); out.flush(); out.close(); Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] {targets[0]}; ProgressObject po = mgr.distribute(targets, rarFile, tempFile); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { TargetModuleID[] ids = po.getResultTargetModuleIDs(); po = mgr.start(ids); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { ids = po.getResultTargetModuleIDs(); if (status != null) { status.getCurrentPool().setName(data.getName()); status.getCurrentPool().setConfigurationName(ids[0].getModuleID()); status.getCurrentPool().setFinished(true); response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } log.info("Deployment completed successfully!"); } } else if (po.getDeploymentStatus().isFailed()) { data.deployError = "Unable to deploy: " + data.name; response.setRenderParameter(MODE_KEY, EDIT_MODE); log.info("Deployment Failed!"); } } } catch (Exception e) { log.error("Unable to save connection pool", e); } finally { if (mgr != null) mgr.release(); } } else { // We're saving updates to an existing pool if (planOnly) { throw new UnsupportedOperationException("Can't update a plan for an existing deployment"); } try { JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean( request, new AbstractName(URI.create(data.getAbstractName()))); if (data.isGeneric()) { factory.setConfigProperty("ConnectionURL", data.getUrl()); factory.setConfigProperty("UserName", data.getUser()); factory.setConfigProperty("Password", data.getPassword()); } else { for (Map.Entry<String, String> entry : data.getProperties().entrySet()) { factory.setConfigProperty(entry.getKey().substring("property-".length()), entry.getValue()); } } //todo: push the lookup into ManagementHelper /* PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer(); pool.setPartitionMinSize( data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize)); pool.setPartitionMaxSize( data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize)); pool.setBlockingTimeoutMilliseconds( data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt( data.blockingTimeout)); pool.setIdleTimeoutMinutes( data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt( data.idleTimeout)); */ } catch (Exception e) { log.error("Unable to save connection pool", e); } } return null; } private static void waitForProgress(ProgressObject po) { while (po.getDeploymentStatus().isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private static ImportStatus getImportStatus(PortletRequest request) { return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus"); } private static File getRAR(PortletRequest request, String rarPath) { org.apache.geronimo.kernel.repository.Artifact artifact = org.apache.geronimo.kernel.repository.Artifact.create( rarPath); ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories(); for (ListableRepository repo : repos) { // if the artifact is not fully resolved then try to resolve it if (!artifact.isResolved()) { SortedSet results = repo.list(artifact); if (!results.isEmpty()) { artifact = (Artifact) results.first(); } else { continue; } } File url = repo.getLocation(artifact); if (url != null) { if (url.exists() && url.canRead() && !url.isDirectory()) { return url; } } } return null; } /** * WARNING: This method relies on having access to the same repository * URLs as the server uses. * * @param request portlet request * @param data info about jars to include * @return driver class */ private static Class attemptDriverLoad(PortletRequest request, PoolData data) { List<URL> list = new ArrayList<URL>(); try { String[] jars = data.getJars(); if (jars == null) { log.error("Driver load failed since no jar files were selected."); return null; } ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories(); for (String jar : jars) { Artifact artifact = Artifact.create( jar); for (ListableRepository repo : repos) { File url = repo.getLocation(artifact); if (url != null) { list.add(url.toURI().toURL()); } } } URLClassLoader loader = new URLClassLoader(list.toArray(new URL[list.size()]), DatabasePoolPortlet.class.getClassLoader()); try { return loader.loadClass(data.driverClass); } catch (ClassNotFoundException e) { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } private static String populateURL(String url, List<String> keys, Map properties) { for (String key : keys) { String value = (String) properties.get("urlproperty-" + key); if (value == null || value.equals("")) { int begin = url.indexOf("{" + key + "}"); int end = begin + key.length() + 2; for (int j = begin - 1; j >= 0; j--) { char c = url.charAt(j); if (c == ';' || c == ':') { begin = j; break; } else if (c == '/') { if (url.length() > end && url.charAt(end) == '/') { begin = j; // Don't leave // if foo is null for /<foo>/ } break; } } url = url.substring(0, begin) + url.substring(end); } else { if (value.indexOf('\\') != -1 || value.indexOf('$') != -1) { // value contains backslash or dollar sign and needs preprocessing for replaceAll to work properly StringBuilder temp = new StringBuilder(); char[] valueChars = value.toCharArray(); for (char valueChar : valueChars) { if (valueChar == '\\' || valueChar == '$') { temp.append('\\'); } temp.append(valueChar); } value = temp.toString(); } url = url.replaceAll("\\{" + key + "\\}", value); } } return url; } private static DatabaseDriver[] getAllDrivers(PortletRequest request) { DatabaseDriver[] result = (DatabaseDriver[]) PortletManager.getGBeansImplementing(request, DatabaseDriver.class); Arrays.sort(result, new Comparator<DatabaseDriver>() { public int compare(DatabaseDriver o1, DatabaseDriver o2) { String name1 = o1.getName(); String name2 = o2.getName(); if (name1.equals("Other")) name1 = "zzzOther"; if (name2.equals("Other")) name2 = "zzzOther"; return name1.compareTo(name2); } }); return result; } private static DatabaseDriver getDatabaseInfo(PortletRequest request, PoolData data) { DatabaseDriver info = null; DatabaseDriver[] all = getAllDrivers(request); for (DatabaseDriver next : all) { if (next.getName().equals(data.getDbtype())) { info = next; break; } } return info; } private static DatabaseDriver getDatabaseInfoFromDriver(PortletRequest request, PoolData data) { DatabaseDriver info = null; DatabaseDriver[] all = getAllDrivers(request); for (DatabaseDriver next : all) { if (next.getDriverClassName() != null && next.getDriverClassName().equals(data.getDriverClass())) { info = next; break; } } return info; } public static class PoolData implements Serializable { private static final long serialVersionUID = 1L; private String name; private String dbtype; private String user; private String password; private Map<String, String> properties = new LinkedHashMap<String, String>(); // Configuration for non-Generic drivers private Map<String, Object> urlProperties = new HashMap<String, Object>(); // URL substitution for Generic drivers private Map<String, String> propertyNames; //todo: store these in the ConfigParam instead private String driverClass; private String url; private String urlPrototype; private String[] jars; private String minSize; private String maxSize; private String blockingTimeout; private String idleTimeout; private String abstractName; private String adapterDisplayName; private String adapterDescription; private String adapterRarPath; private String rarPath; private String transactionType; private String importSource; private Map<String, String> abstractNameMap; // generated as needed, don't need to read/write it private String deployError; public void load(PortletRequest request) { name = request.getParameter("name"); if (name != null && name.equals("")) name = null; driverClass = request.getParameter("driverClass"); if (driverClass != null && driverClass.equals("")) driverClass = null; dbtype = request.getParameter("dbtype"); if (dbtype != null && dbtype.equals("")) dbtype = null; user = request.getParameter("user"); if (user != null && user.equals("")) user = null; password = request.getParameter("password"); if (password != null && password.equals("")) password = null; url = request.getParameter("url"); if (url != null && url.equals("")) { url = null; } else if (url != null && url.startsWith("URLENCODED")) { try { url = URLDecoder.decode(url.substring(10), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to decode URL", e); } catch (IllegalArgumentException e) { // not encoded after all?? url = url.substring(10); } } urlPrototype = request.getParameter("urlPrototype"); if (urlPrototype != null && urlPrototype.equals("")) urlPrototype = null; jars = request.getParameterValues("jars"); minSize = request.getParameter("minSize"); if (minSize != null && minSize.equals("")) minSize = null; maxSize = request.getParameter("maxSize"); if (maxSize != null && maxSize.equals("")) maxSize = null; blockingTimeout = request.getParameter("blockingTimeout"); if (blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null; idleTimeout = request.getParameter("idleTimeout"); if (idleTimeout != null && idleTimeout.equals("")) idleTimeout = null; abstractName = request.getParameter("abstractName"); if (abstractName != null && abstractName.equals("")) abstractName = null; adapterDisplayName = request.getParameter("adapterDisplayName"); if (adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null; adapterDescription = request.getParameter("adapterDescription"); if (adapterDescription != null && adapterDescription.equals("")) adapterDescription = null; rarPath = request.getParameter("rarPath"); if (rarPath != null && rarPath.equals("")) rarPath = null; importSource = request.getParameter("importSource"); if (importSource != null && importSource.equals("")) importSource = null; transactionType = request.getParameter("transactionType"); if (transactionType != null && "".equals(transactionType)) { if (dbtype != null && dbtype.endsWith("XA")) { transactionType = XA; } else { transactionType = LOCAL; } } Map map = request.getParameterMap(); propertyNames = new HashMap<String, String>(); for (Object o : map.keySet()) { String key = (String) o; if (key.startsWith("urlproperty-")) { urlProperties.put(key, request.getParameter(key)); } else if (key.startsWith("property-")) { properties.put(key, request.getParameter(key)); propertyNames.put(key, getPropertyName(key)); } } sort(); deployError = request.getParameter("deployError"); if (deployError != null && deployError.equals("")) deployError = null; } public void loadPropertyNames() { propertyNames = new HashMap<String, String>(); for (String key : properties.keySet()) { propertyNames.put(key, getPropertyName(key)); } } private static String getPropertyName(String key) { int pos = key.indexOf('-'); key = Character.toUpperCase(key.charAt(pos + 1)) + key.substring(pos + 2); StringBuilder buf = new StringBuilder(); pos = 0; for (int i = 1; i < key.length(); i++) { if(key.charAt(i)=='_') { buf.append(key.substring(pos, i)).append(" "); pos = i+1; } else{ if (Character.isUpperCase(key.charAt(i))) { if (Character.isUpperCase(key.charAt(i - 1)) || key.charAt(i-1)=='_') { // ongoing capitalized word } else { // start of a new word buf.append(key.substring(pos, i)).append(" "); pos = i; } } else { if (Character.isUpperCase( key.charAt(i - 1)) && i - pos > 1) { // first lower-case after a series of caps buf.append(key.substring(pos, i - 1)).append(" "); pos = i - 1; } } } } buf.append(key.substring(pos)); return buf.toString(); } public void store(ActionResponse response) { if (name != null) response.setRenderParameter("name", name); if (dbtype != null) response.setRenderParameter("dbtype", dbtype); if (driverClass != null) response.setRenderParameter("driverClass", driverClass); if (user != null) response.setRenderParameter("user", user); if (password != null) response.setRenderParameter("password", password); if (url != null) { // attempt to work around Pluto/Tomcat error with ; in a stored value try { response.setRenderParameter("url", "URLENCODED" + URLEncoder.encode(url, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to encode URL", e); } } if (urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype); if (jars != null) response.setRenderParameter("jars", jars); if (minSize != null) response.setRenderParameter("minSize", minSize); if (maxSize != null) response.setRenderParameter("maxSize", maxSize); if (blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout); if (idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout); if (abstractName != null) response.setRenderParameter("abstractName", abstractName); if (adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName); if (adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription); if (importSource != null) response.setRenderParameter("importSource", importSource); if (rarPath != null) response.setRenderParameter("rarPath", rarPath); if (transactionType != null) response.setRenderParameter("transactionType", transactionType); for (Map.Entry<String, Object> entry : urlProperties.entrySet()) { if (entry.getValue() != null) { response.setRenderParameter(entry.getKey(), entry.getValue().toString()); } } for (Map.Entry<String, String> entry : properties.entrySet()) { if (entry.getValue() != null) { response.setRenderParameter(entry.getKey(), entry.getValue()); } } if (deployError != null) response.setRenderParameter("deployError", deployError); } public void sort() { Map<String, String> sortedProperties = new LinkedHashMap<String, String>(); for (String propertyName : ORDERED_PROPERTY_NAMES) { if (properties.containsKey(propertyName)) { sortedProperties.put(propertyName, properties.get(propertyName)); properties.remove(propertyName); } } sortedProperties.putAll(properties); properties = sortedProperties; } public String getName() { return name; } public String getDbtype() { return dbtype; } public String getUser() { return user; } public String getPassword() { return password; } public Map<String, String> getProperties() { return properties; } public Map<String, String> getPropertyNames() { return propertyNames; } public Map<String, Object> getUrlProperties() { return urlProperties; } public String getUrl() { return url; } public String[] getJars() { return jars; } public String getMinSize() { return minSize; } public String getMaxSize() { return maxSize; } public String getBlockingTimeout() { return blockingTimeout; } public String getIdleTimeout() { return idleTimeout; } public String getDriverClass() { return driverClass; } public String getUrlPrototype() { return urlPrototype; } public String getAbstractName() { return abstractName; } public String getAdapterDisplayName() { return adapterDisplayName; } public String getAdapterDescription() { return adapterDescription; } public String getAdapterRarPath() { return adapterRarPath; } public String getRarPath() { return rarPath; } public boolean isGeneric() { //todo: is there any better way to tell? return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter"); } public String getImportSource() { return importSource; } public Map<String, String> getAbstractNameMap() { if (abstractName == null) return Collections.emptyMap(); if (abstractNameMap != null) return abstractNameMap; AbstractName name = new AbstractName(URI.create(abstractName)); abstractNameMap = new HashMap<String, String>(name.getName()); abstractNameMap.put("domain", name.getObjectName().getDomain()); abstractNameMap.put("groupId", name.getArtifact().getGroupId()); abstractNameMap.put("artifactId", name.getArtifact().getArtifactId()); abstractNameMap.put("type", name.getArtifact().getType()); abstractNameMap.put("version", name.getArtifact().getVersion().toString()); return abstractNameMap; } public String getDeployError() { return deployError; } public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } } public static class ConnectionPool implements Serializable, Comparable { private static final long serialVersionUID = 1L; private final String adapterAbstractName; private final String factoryAbstractName; private final String name; private final String parentName; private final int state; public ConnectionPool(AbstractName adapterAbstractName, AbstractName factoryAbstractName, String name, int state) { this.adapterAbstractName = adapterAbstractName.toURI().toString(); String parent = (String) adapterAbstractName.getName().get(NameFactory.J2EE_APPLICATION); if (parent != null && parent.equals("null")) { parent = null; } parentName = parent; this.factoryAbstractName = factoryAbstractName.toURI().toString(); this.name = name; this.state = state; } public String getAdapterAbstractName() { return adapterAbstractName; } public String getFactoryAbstractName() { return factoryAbstractName; } public String getName() { return name; } public String getParentName() { return parentName; } public int getState() { return state; } public String getStateName() { return State.toString(state); } public int compareTo(Object o) { final ConnectionPool pool = (ConnectionPool) o; int names = name.compareTo(pool.name); if (parentName == null) { if (pool.parentName == null) { return names; } else { return -1; } } else { if (pool.parentName == null) { return 1; } else { int test = parentName.compareTo(pool.parentName); if (test != 0) { return test; } else { return names; } } } } } public static class ResourceAdapterParams { private String displayName; private String description; private String rarPath; private ConfigParam[] configParams; public ResourceAdapterParams(String displayName, String description, String rarPath, ConfigParam[] configParams) { this.displayName = displayName; this.description = description; this.rarPath = rarPath; this.configParams = configParams; } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public String getRarPath() { return rarPath; } public ConfigParam[] getConfigParams() { return configParams; } } public static class ConfigParam { private String name; private String type; private String description; private String defaultValue; public ConfigParam(String name, String type, String description, String defaultValue) { this.name = name; this.type = type; this.description = description; this.defaultValue = defaultValue; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public String getDefaultValue() { return defaultValue; } } }
plugins/system-database/sysdb-portlets/src/main/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java
/** * 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.geronimo.console.databasemanager.wizard; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.net.URLEncoder; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.SortedSet; import javax.enterprise.deploy.model.DDBean; import javax.enterprise.deploy.model.DDBeanRoot; import javax.enterprise.deploy.shared.ModuleType; import javax.enterprise.deploy.spi.DeploymentConfiguration; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.TargetModuleID; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletRequestDispatcher; import javax.portlet.PortletSession; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.portlet.PortletFileUpload; import org.apache.geronimo.connector.deployment.jsr88.ConfigPropertySetting; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinition; import org.apache.geronimo.connector.deployment.jsr88.ConnectionDefinitionInstance; import org.apache.geronimo.connector.deployment.jsr88.ConnectionManager; import org.apache.geronimo.connector.deployment.jsr88.Connector15DCBRoot; import org.apache.geronimo.connector.deployment.jsr88.ConnectorDCB; import org.apache.geronimo.connector.deployment.jsr88.ResourceAdapter; import org.apache.geronimo.connector.deployment.jsr88.SinglePool; import org.apache.geronimo.connector.outbound.PoolingAttributes; import org.apache.geronimo.console.BasePortlet; import org.apache.geronimo.console.ajax.ProgressInfo; import org.apache.geronimo.console.databasemanager.ManagementHelper; import org.apache.geronimo.console.util.PortletManager; import org.apache.geronimo.converter.DatabaseConversionStatus; import org.apache.geronimo.converter.JDBCPool; import org.apache.geronimo.converter.bea.WebLogic81DatabaseConverter; import org.apache.geronimo.converter.jboss.JBoss4DatabaseConverter; import org.apache.geronimo.deployment.service.jsr88.EnvironmentData; import org.apache.geronimo.deployment.tools.loader.ConnectorDeployable; import org.apache.geronimo.gbean.AbstractName; import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory; import org.apache.geronimo.kernel.GBeanNotFoundException; import org.apache.geronimo.kernel.InternalKernelException; import org.apache.geronimo.kernel.KernelRegistry; import org.apache.geronimo.kernel.config.ConfigurationManager; import org.apache.geronimo.kernel.config.ConfigurationUtil; import org.apache.geronimo.kernel.management.State; import org.apache.geronimo.kernel.proxy.GeronimoManagedBean; import org.apache.geronimo.kernel.repository.Artifact; import org.apache.geronimo.kernel.repository.FileWriteMonitor; import org.apache.geronimo.kernel.repository.ListableRepository; import org.apache.geronimo.kernel.repository.WriteableRepository; import org.apache.geronimo.kernel.util.XmlUtil; import org.apache.geronimo.management.geronimo.JCAManagedConnectionFactory; import org.apache.geronimo.management.geronimo.ResourceAdapterModule; import org.apache.geronimo.system.plugin.PluginInstallerGBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; /** * A portlet that lets you configure and deploy JDBC connection pools. * * @version $Rev$ $Date$ */ public class DatabasePoolPortlet extends BasePortlet { private static final Logger log = LoggerFactory.getLogger(DatabasePoolPortlet.class); private final static Set<String> INCLUDE_ARTIFACTIDS = new HashSet<String>(Arrays.asList("system-database")); private final static Set<String> EXCLUDE_GROUPIDS = new HashSet<String>(Arrays.asList("org.apache.geronimo.modules", "org.apache.geronimo.configs", "org.apache.geronimo.applications", "org.apache.geronimo.assemblies", "org.apache.cxf", "org.apache.tomcat", "org.tranql", "commons-cli", "commons-io", "commons-logging", "commons-lang", "axis", "org.apache.axis2", "org.apache.directory", "org.apache.activemq", "org.apache.openejb", "org.apache.myfaces", "org.mortbay.jetty")); private final static String DRIVER_SESSION_KEY = "org.apache.geronimo.console.dbpool.Drivers"; private final static String CONFIG_SESSION_KEY = "org.apache.geronimo.console.dbpool.ConfigParam"; private final static String DRIVER_INFO_URL = "http://geronimo.apache.org/driver-downloads.properties"; private static final String LIST_VIEW = "/WEB-INF/view/dbwizard/list.jsp"; private static final String EDIT_VIEW = "/WEB-INF/view/dbwizard/edit.jsp"; private static final String SELECT_RDBMS_VIEW = "/WEB-INF/view/dbwizard/selectDatabase.jsp"; private static final String BASIC_PARAMS_VIEW = "/WEB-INF/view/dbwizard/basicParams.jsp"; private static final String CONFIRM_URL_VIEW = "/WEB-INF/view/dbwizard/confirmURL.jsp"; private static final String TEST_CONNECTION_VIEW = "/WEB-INF/view/dbwizard/testConnection.jsp"; private static final String DOWNLOAD_VIEW = "/WEB-INF/view/dbwizard/selectDownload.jsp"; private static final String DOWNLOAD_STATUS_VIEW = "/WEB-INF/view/dbwizard/downloadStatus.jsp"; private static final String SHOW_PLAN_VIEW = "/WEB-INF/view/dbwizard/showPlan.jsp"; private static final String IMPORT_UPLOAD_VIEW = "/WEB-INF/view/dbwizard/importUpload.jsp"; private static final String IMPORT_STATUS_VIEW = "/WEB-INF/view/dbwizard/importStatus.jsp"; private static final String USAGE_VIEW = "/WEB-INF/view/dbwizard/usage.jsp"; private static final String LIST_MODE = "list"; private static final String EDIT_MODE = "edit"; private static final String SELECT_RDBMS_MODE = "rdbms"; private static final String BASIC_PARAMS_MODE = "params"; private static final String CONFIRM_URL_MODE = "url"; private static final String TEST_CONNECTION_MODE = "test"; private static final String SHOW_PLAN_MODE = "plan"; private static final String DOWNLOAD_MODE = "download"; private static final String DOWNLOAD_STATUS_MODE = "downloadStatus"; private static final String EDIT_EXISTING_MODE = "editExisting"; private static final String DELETE_MODE = "delete"; private static final String SAVE_MODE = "save"; private static final String IMPORT_START_MODE = "startImport"; private static final String IMPORT_UPLOAD_MODE = "importUpload"; private static final String IMPORT_STATUS_MODE = "importStatus"; private static final String IMPORT_COMPLETE_MODE = "importComplete"; private static final String WEBLOGIC_IMPORT_MODE = "weblogicImport"; private static final String USAGE_MODE = "usage"; private static final String IMPORT_EDIT_MODE = "importEdit"; private static final String MODE_KEY = "mode"; private static final String LOCAL = "LOCAL"; private static final String XA = "XA"; private static final String NONE = "NONE"; private static final String[] ORDERED_PROPERTY_NAMES = { "property-DatabaseName", "property-CreateDatabase", "property-UserName", "property-Password" }; private PortletRequestDispatcher listView; private PortletRequestDispatcher editView; private PortletRequestDispatcher selectRDBMSView; private PortletRequestDispatcher basicParamsView; private PortletRequestDispatcher confirmURLView; private PortletRequestDispatcher testConnectionView; private PortletRequestDispatcher downloadView; private PortletRequestDispatcher downloadStatusView; private PortletRequestDispatcher planView; private PortletRequestDispatcher importUploadView; private PortletRequestDispatcher importStatusView; private PortletRequestDispatcher usageView; private Map<String, String> rarPathMap; public void init(PortletConfig portletConfig) throws PortletException { super.init(portletConfig); listView = portletConfig.getPortletContext().getRequestDispatcher(LIST_VIEW); editView = portletConfig.getPortletContext().getRequestDispatcher(EDIT_VIEW); selectRDBMSView = portletConfig.getPortletContext().getRequestDispatcher(SELECT_RDBMS_VIEW); basicParamsView = portletConfig.getPortletContext().getRequestDispatcher(BASIC_PARAMS_VIEW); confirmURLView = portletConfig.getPortletContext().getRequestDispatcher(CONFIRM_URL_VIEW); testConnectionView = portletConfig.getPortletContext().getRequestDispatcher(TEST_CONNECTION_VIEW); downloadView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_VIEW); downloadStatusView = portletConfig.getPortletContext().getRequestDispatcher(DOWNLOAD_STATUS_VIEW); planView = portletConfig.getPortletContext().getRequestDispatcher(SHOW_PLAN_VIEW); importUploadView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_UPLOAD_VIEW); importStatusView = portletConfig.getPortletContext().getRequestDispatcher(IMPORT_STATUS_VIEW); usageView = portletConfig.getPortletContext().getRequestDispatcher(USAGE_VIEW); rarPathMap = new HashMap<String, String>(); rarPathMap.put("TranQL XA Resource Adapter for DB2", "tranql-connector-db2-xa"); rarPathMap.put("TranQL Client Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-client-local"); rarPathMap.put("TranQL Client XA Resource Adapter for Apache Derby", "tranql-connector-derby-client-xa"); // rarPathMap.put("TranQL Embedded Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); // rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-xa"); rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); rarPathMap.put("TranQL XA Resource Adapter for Informix", "tranql-connector-informix-xa"); rarPathMap.put("TranQL Client Local Transaction Resource Adapter for MySQL", "tranql-connector-mysql-local"); rarPathMap.put("TranQL Client XA Resource Adapter for MySQL", "tranql-connector-mysql-xa"); rarPathMap.put("TranQL Local Resource Adapter for Oracle", "tranql-connector-oracle-local"); rarPathMap.put("TranQL XA Resource Adapter for Oracle", "tranql-connector-oracle-xa"); rarPathMap.put("TranQL Local Resource Adapter for PostgreSQL", "tranql-connector-postgresql-local"); rarPathMap.put("TranQL XA Resource Adapter for PostgreSQL", "tranql-connector-postgresql-xa"); rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2000", "tranql-connector-sqlserver2000-xa"); rarPathMap.put("TranQL XA Resource Adapter for SQLServer 2005", "tranql-connector-sqlserver2005-xa"); } public void destroy() { listView = null; editView = null; selectRDBMSView = null; basicParamsView = null; confirmURLView = null; testConnectionView = null; downloadView = null; downloadStatusView = null; planView = null; importUploadView = null; importStatusView = null; usageView = null; rarPathMap.clear(); super.destroy(); } public DriverDownloader.DriverInfo[] getDriverInfo(PortletRequest request) { PortletSession session = request.getPortletSession(true); DriverDownloader.DriverInfo[] results = (DriverDownloader.DriverInfo[]) session.getAttribute(DRIVER_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if (results == null || results.length ==0) { DriverDownloader downloader = new DriverDownloader(); try { results = downloader.loadDriverInfo(new URL(DRIVER_INFO_URL)); session.setAttribute(DRIVER_SESSION_KEY, results, PortletSession.APPLICATION_SCOPE); } catch (MalformedURLException e) { log.error("Unable to download driver data", e); results = new DriverDownloader.DriverInfo[0]; } } return results; } /** * Loads data about a resource adapter. Depending on what we already have, may load * the name and description, but always loads the config property descriptions. * * @param request Pass it or die * @param rarPath If we're creating a new RA, the path to identify it * @param displayName If we're editing an existing RA, its name * @param adapterAbstractName If we're editing an existing RA, its AbstractName * @return resource adapter parameter data object */ public ResourceAdapterParams getRARConfiguration(PortletRequest request, String rarPath, String displayName, String adapterAbstractName) { PortletSession session = request.getPortletSession(true); if (rarPath != null && !rarPath.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute( CONFIG_SESSION_KEY + "-" + rarPath, PortletSession.APPLICATION_SCOPE); if (results == null) { results = loadConfigPropertiesByPath(request, rarPath); session.setAttribute(CONFIG_SESSION_KEY + "-" + rarPath, results, PortletSession.APPLICATION_SCOPE); session.setAttribute(CONFIG_SESSION_KEY + "-" + results.displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else if (displayName != null && !displayName.equals( "") && adapterAbstractName != null && !adapterAbstractName.equals("")) { ResourceAdapterParams results = (ResourceAdapterParams) session.getAttribute( CONFIG_SESSION_KEY + "-" + displayName, PortletSession.APPLICATION_SCOPE); if (results == null) { results = loadConfigPropertiesByAbstractName(request, rarPathMap.get(displayName), adapterAbstractName); session.setAttribute(CONFIG_SESSION_KEY + "-" + displayName, results, PortletSession.APPLICATION_SCOPE); } return results; } else { throw new IllegalArgumentException(); } } public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter(MODE_KEY); if (mode.equals(IMPORT_UPLOAD_MODE)) { processImportUpload(actionRequest, actionResponse); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); return; } PoolData data = new PoolData(); data.load(actionRequest); if (mode.equals("process-" + SELECT_RDBMS_MODE)) { DatabaseDriver info = getDatabaseInfo(actionRequest, data); if (info != null) { data.rarPath = info.getRAR().toString(); if (info.isSpecific()) { data.adapterDisplayName = "Unknown"; // will pick these up when we process the RA type in the render request data.adapterDescription = "Unknown"; actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { data.driverClass = info.getDriverClassName(); data.urlPrototype = info.getURLPrototype(); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else { actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE); } } else if (mode.equals("process-" + DOWNLOAD_MODE)) { String name = actionRequest.getParameter("driverName"); DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest); DriverDownloader.DriverInfo found = null; for (DriverDownloader.DriverInfo driver : drivers) { if (driver.getName().equals(name)) { found = driver; break; } } if (found != null) { data.jars = new String[]{found.getRepositoryURI()}; try { PluginInstallerGBean installer = KernelRegistry.getSingleKernel().getGBean(PluginInstallerGBean.class); //WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0]; final PortletSession session = actionRequest.getPortletSession(); ProgressInfo progressInfo = new ProgressInfo(); progressInfo.setMainMessage("Downloading " + found.getName()); session.setAttribute(ProgressInfo.PROGRESS_INFO_KEY, progressInfo, PortletSession.APPLICATION_SCOPE); // Start the download monitoring new Thread(new Downloader(found, progressInfo, installer)).start(); actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_STATUS_MODE); } catch (GBeanNotFoundException e) { throw new PortletException(e); } catch (InternalKernelException e) { throw new PortletException(e); } catch (IllegalStateException e) { throw new PortletException(e); } } else { actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_MODE); } } else if (mode.equals("process-" + DOWNLOAD_STATUS_MODE)) { if (data.getDbtype() == null || data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } else { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } } else if (mode.equals("process-" + BASIC_PARAMS_MODE)) { DatabaseDriver info; info = getDatabaseInfo(actionRequest, data); if (info != null) { data.url = populateURL(info.getURLPrototype(), info.getURLParameters(), data.getUrlProperties()); } if (attemptDriverLoad(actionRequest, data) != null) { actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE); } else { actionResponse.setRenderParameter("driverError", "Unable to load driver " + data.driverClass); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if (mode.equals("process-" + CONFIRM_URL_MODE)) { String test = actionRequest.getParameter("test"); if (test == null || test.equals("true")) { try { String targetDBInfo = attemptConnect(actionRequest, data); actionResponse.setRenderParameter("targetDBInfo", targetDBInfo); actionResponse.setRenderParameter("connected", "true"); } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter temp = new PrintWriter(writer); e.printStackTrace(temp); temp.flush(); temp.close(); addErrorMessage(actionRequest, getLocalizedString(actionRequest, "dbwizard.testConnection.connectionError"), writer.getBuffer().toString()); actionResponse.setRenderParameter("connected", "false"); } actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE); } else { save(actionRequest, actionResponse, data, false); } } else if (mode.equals(SAVE_MODE)) { save(actionRequest, actionResponse, data, false); } else if (mode.equals(SHOW_PLAN_MODE)) { String plan = save(actionRequest, actionResponse, data, true); actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan); actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE); } else if (mode.equals(EDIT_EXISTING_MODE)) { final String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); actionResponse.setRenderParameter("adapterAbstractName", name); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(SELECT_RDBMS_MODE)) { if (data.getAdapterDisplayName() == null) { // Set a default for a new pool data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; } actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(WEBLOGIC_IMPORT_MODE)) { String domainDir = actionRequest.getParameter("weblogicDomainDir"); String libDir = actionRequest.getParameter("weblogicLibDir"); try { DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir); actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } catch (Exception e) { log.error("Unable to import", e); actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE); } } else if (mode.equals(IMPORT_START_MODE)) { actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(IMPORT_EDIT_MODE)) { ImportStatus status = getImportStatus(actionRequest); int index = Integer.parseInt(actionRequest.getParameter("importIndex")); status.setCurrentPoolIndex(index); loadImportedData(actionRequest, data, status.getCurrentPool()); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(IMPORT_COMPLETE_MODE)) { ImportStatus status = getImportStatus(actionRequest); log.warn("Import Results:"); //todo: create a screen for this log.warn(" " + status.getSkippedCount() + " ignored"); log.warn(" " + status.getStartedCount() + " reviewed but not deployed"); log.warn(" " + status.getPendingCount() + " not reviewed"); log.warn(" " + status.getFinishedCount() + " deployed"); actionRequest.getPortletSession().removeAttribute("ImportStatus"); } else if (mode.equals(DELETE_MODE)) { String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); delete(actionRequest, actionResponse, data); } else { actionResponse.setRenderParameter(MODE_KEY, mode); } data.store(actionResponse); } private static class Downloader implements Runnable { private PluginInstallerGBean installer; private DriverDownloader.DriverInfo driver; private ProgressInfo progressInfo; public Downloader(DriverDownloader.DriverInfo driver, ProgressInfo progressInfo, PluginInstallerGBean installer) { this.driver = driver; this.progressInfo = progressInfo; this.installer = installer; } public void run() { DriverDownloader downloader = new DriverDownloader(); try { downloader.loadDriver(installer, driver, new FileWriteMonitor() { private int fileSize; public void writeStarted(String fileDescription, int fileSize) { this.fileSize = fileSize; log.info("Downloading " + fileDescription); } public void writeProgress(int bytes) { int kbDownloaded = (int) Math.floor(bytes / 1024); if (fileSize > 0) { int percent = (bytes * 100) / fileSize; progressInfo.setProgressPercent(percent); progressInfo.setSubMessage(kbDownloaded + " / " + fileSize / 1024 + " Kb downloaded"); } else { progressInfo.setSubMessage(kbDownloaded + " Kb downloaded"); } } public void writeComplete(int bytes) { log.info("Finished downloading " + bytes + " b"); } }); } catch (IOException e) { log.error("Unable to download database driver", e); } finally { progressInfo.setFinished(true); } } } private void loadImportedData(PortletRequest request, PoolData data, ImportStatus.PoolProgress progress) throws PortletException { if (!progress.getType().equals(ImportStatus.PoolProgress.TYPE_XA)) { JDBCPool pool = (JDBCPool) progress.getPool(); data.dbtype = "Other"; data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; data.blockingTimeout = getImportString(pool.getBlockingTimeoutMillis()); data.driverClass = pool.getDriverClass(); data.idleTimeout = pool.getIdleTimeoutMillis() != null ? Integer.toString( pool.getIdleTimeoutMillis().intValue() / (60 * 1000)) : null; data.maxSize = getImportString(pool.getMaxSize()); data.minSize = getImportString(pool.getMinSize()); data.name = pool.getName(); data.password = pool.getPassword(); data.url = pool.getJdbcURL(); data.user = pool.getUsername(); if (pool.getDriverClass() != null) { DatabaseDriver info = getDatabaseInfoFromDriver(request, data); if (info != null) { data.rarPath = info.getRAR().toString(); data.urlPrototype = info.getURLPrototype(); } else { throw new PortletException("Don't recognize database driver " + data.driverClass + "!"); } } } else { //todo: handle XA } } private static String getImportString(Integer value) { return value == null ? null : value.toString(); } private boolean processImportUpload(ActionRequest request, ActionResponse response) throws PortletException { String type = request.getParameter("importSource"); response.setRenderParameter("importSource", type); if (!PortletFileUpload.isMultipartContent(request)) { throw new PortletException("Expected file upload"); } PortletFileUpload uploader = new PortletFileUpload(new DiskFileItemFactory()); try { List<FileItem> items = uploader.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = File.createTempFile("geronimo-import", ""); file.deleteOnExit(); log.debug("Writing database pool import file to " + file.getAbsolutePath()); item.write(file); DatabaseConversionStatus status = processImport(file, type); request.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); return true; } else { throw new PortletException("Not expecting any form fields"); } } } catch (PortletException e) { throw e; } catch (Exception e) { throw new PortletException(e); } return false; } private DatabaseConversionStatus processImport(File importFile, String type) throws PortletException, IOException { if (type.equals("JBoss 4")) { return JBoss4DatabaseConverter.convert(new FileReader(importFile)); } else if (type.equals("WebLogic 8.1")) { return WebLogic81DatabaseConverter.convert(new FileReader(importFile)); } else { throw new PortletException("Unknown import type '" + type + "'"); } } private ResourceAdapterParams loadConfigPropertiesByPath(PortletRequest request, String rarPath) { DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { //URI uri = getRAR(request, rarPath).toURI(); ConnectorDeployable deployable = new ConnectorDeployable(PortletManager.getRepositoryEntryBundle(request, rarPath)); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); String adapterName = null, adapterDesc = null; String[] test = ddBeanRoot.getText("connector/display-name"); if (test != null && test.length > 0) { adapterName = test[0]; } test = ddBeanRoot.getText("connector/description"); if (test != null && test.length > 0) { adapterDesc = test[0]; } DDBean[] definitions = ddBeanRoot.getChildBean( "connector/resourceadapter/outbound-resourceadapter/connection-definition"); List<ConfigParam> configs = new ArrayList<ConfigParam>(); if (definitions != null) { for (DDBean definition : definitions) { String iface = definition.getText("connectionfactory-interface")[0]; if (iface.equals("javax.sql.DataSource")) { DDBean[] beans = definition.getChildBean("config-property"); for (DDBean bean : beans) { String name = bean.getText("config-property-name")[0].trim(); String type = bean.getText("config-property-type")[0].trim(); test = bean.getText("config-property-value"); String value = test == null || test.length == 0 ? null : test[0].trim(); test = bean.getText("description"); String desc = test == null || test.length == 0 ? null : test[0].trim(); configs.add(new ConfigParam(name, type, desc, value)); } } } } return new ResourceAdapterParams(adapterName, adapterDesc, rarPath.substring(11, rarPath.length()-5), configs.toArray(new ConfigParam[configs.size()])); } catch (Exception e) { log.error("Unable to read configuration properties", e); return null; } finally { if (mgr != null) mgr.release(); } } private ResourceAdapterParams loadConfigPropertiesByAbstractName(PortletRequest request, String rarPath, String abstractName) { ResourceAdapterModule module = (ResourceAdapterModule) PortletManager.getManagedBean(request, new AbstractName(URI.create(abstractName))); String dd = module.getDeploymentDescriptor(); DocumentBuilderFactory factory = XmlUtil.newDocumentBuilderFactory(); factory.setValidating(false); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); final StringReader reader = new StringReader(dd); Document doc = builder.parse(new InputSource(reader)); reader.close(); Element elem = doc.getDocumentElement(); // connector String displayName = getFirstText(elem.getElementsByTagName("display-name")); String description = getFirstText(elem.getElementsByTagName("description")); elem = (Element) elem.getElementsByTagName("resourceadapter").item(0); elem = (Element) elem.getElementsByTagName("outbound-resourceadapter").item(0); NodeList defs = elem.getElementsByTagName("connection-definition"); List<ConfigParam> all = new ArrayList<ConfigParam>(); for (int i = 0; i < defs.getLength(); i++) { final Element def = (Element) defs.item(i); String iface = getFirstText(def.getElementsByTagName("connectionfactory-interface")).trim(); if (iface.equals("javax.sql.DataSource")) { NodeList configs = def.getElementsByTagName("config-property"); for (int j = 0; j < configs.getLength(); j++) { Element config = (Element) configs.item(j); String name = getFirstText(config.getElementsByTagName("config-property-name")).trim(); String type = getFirstText(config.getElementsByTagName("config-property-type")).trim(); String test = getFirstText(config.getElementsByTagName("config-property-value")); String value = test == null ? null : test.trim(); test = getFirstText(config.getElementsByTagName("description")); String desc = test == null ? null : test.trim(); all.add(new ConfigParam(name, type, desc, value)); } } } return new ResourceAdapterParams(displayName, description, rarPath, all.toArray(new ConfigParam[all.size()])); } catch (Exception e) { log.error("Unable to read resource adapter DD", e); return null; } } private String getFirstText(NodeList list) { if (list.getLength() == 0) { return null; } Element first = (Element) list.item(0); StringBuilder buf = new StringBuilder(); NodeList all = first.getChildNodes(); for (int i = 0; i < all.getLength(); i++) { Node node = all.item(i); if (node.getNodeType() == Node.TEXT_NODE) { buf.append(node.getNodeValue()); } } return buf.toString(); } private void loadConnectionFactory(ActionRequest actionRequest, String adapterName, String factoryName, PoolData data) { AbstractName abstractAdapterName = new AbstractName(URI.create(adapterName)); AbstractName abstractFactoryName = new AbstractName(URI.create(factoryName)); ResourceAdapterModule adapter = (ResourceAdapterModule) PortletManager.getManagedBean(actionRequest, abstractAdapterName); JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean(actionRequest, abstractFactoryName); data.adapterDisplayName = adapter.getDisplayName(); data.adapterDescription = adapter.getDescription(); try { data.name = (String) abstractFactoryName.getName().get("name"); if (data.isGeneric()) { data.url = (String) factory.getConfigProperty("ConnectionURL"); data.driverClass = (String) factory.getConfigProperty("Driver"); data.user = (String) factory.getConfigProperty("UserName"); data.password = (String) factory.getConfigProperty("Password"); } else { ResourceAdapterParams params = getRARConfiguration(actionRequest, data.getRarPath(), data.getAdapterDisplayName(), adapterName); for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam cp = params.getConfigParams()[i]; Object value = factory.getConfigProperty(cp.getName()); data.properties.put("property-" + cp.getName(), value == null ? null : value.toString()); } data.sort(); } } catch (Exception e) { log.error("Unable to look up connection property", e); } //todo: push the lookup into ManagementHelper /* PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer(); data.minSize = Integer.toString(pool.getPartitionMinSize()); data.maxSize = Integer.toString(pool.getPartitionMaxSize()); data.blockingTimeout = Integer.toString(pool.getBlockingTimeoutMilliseconds()); data.idleTimeout = Integer.toString(pool.getIdleTimeoutMinutes()); */ } protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { if (WindowState.MINIMIZED.equals(renderRequest.getWindowState())) { return; } try { String mode = renderRequest.getParameter(MODE_KEY); PoolData data = new PoolData(); data.load(renderRequest); renderRequest.setAttribute("pool", data); // If not headed anywhere in particular, send to list if (mode == null || mode.equals("")) { mode = LIST_MODE; } // If headed to list but there's an import in progress, redirect to import status if (mode.equals(LIST_MODE) && getImportStatus(renderRequest) != null) { mode = IMPORT_STATUS_MODE; } if (mode.equals(LIST_MODE)) { renderList(renderRequest, renderResponse); } else if (mode.equals(EDIT_MODE)) { renderEdit(renderRequest, renderResponse, data); } else if (mode.equals(SELECT_RDBMS_MODE)) { renderSelectRDBMS(renderRequest, renderResponse); } else if (mode.equals(DOWNLOAD_MODE)) { renderDownload(renderRequest, renderResponse); } else if (mode.equals(DOWNLOAD_STATUS_MODE)) { renderDownloadStatus(renderRequest, renderResponse); } else if (mode.equals(BASIC_PARAMS_MODE)) { renderBasicParams(renderRequest, renderResponse, data); } else if (mode.equals(CONFIRM_URL_MODE)) { renderConfirmURL(renderRequest, renderResponse); } else if (mode.equals(TEST_CONNECTION_MODE)) { renderTestConnection(renderRequest, renderResponse); } else if (mode.equals(SHOW_PLAN_MODE)) { renderPlan(renderRequest, renderResponse, data); } else if (mode.equals(IMPORT_START_MODE)) { renderImportUploadForm(renderRequest, renderResponse); } else if (mode.equals(IMPORT_STATUS_MODE)) { renderImportStatus(renderRequest, renderResponse); } else if (mode.equals(USAGE_MODE)) { renderUsage(renderRequest, renderResponse); } } catch (Throwable e) { log.error("Unable to render portlet", e); } } private void renderUsage(RenderRequest request, RenderResponse response) throws IOException, PortletException { usageView.include(request, response); } private void renderImportStatus(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("status", getImportStatus(request)); populatePoolList(request); importStatusView.include(request, response); } private void renderImportUploadForm(RenderRequest request, RenderResponse response) throws IOException, PortletException { request.setAttribute("from", request.getParameter("from")); importUploadView.include(request, response); } private void renderList(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { populatePoolList(renderRequest); listView.include(renderRequest, renderResponse); } private void populatePoolList(PortletRequest renderRequest) { ResourceAdapterModule[] modules = PortletManager.getOutboundRAModules(renderRequest, "javax.sql.DataSource"); List<ConnectionPool> list = new ArrayList<ConnectionPool>(); for (ResourceAdapterModule module : modules) { AbstractName moduleName = PortletManager.getManagementHelper(renderRequest).getNameFor(module); JCAManagedConnectionFactory[] databases = PortletManager.getOutboundFactoriesForRA(renderRequest, module, "javax.sql.DataSource"); for (JCAManagedConnectionFactory db : databases) { AbstractName dbName = PortletManager.getManagementHelper(renderRequest).getNameFor(db); list.add(new ConnectionPool(moduleName, dbName, (String) dbName.getName().get(NameFactory.J2EE_NAME), PortletManager.getManagedBean(renderRequest, dbName).getState())); } } Collections.sort(list); renderRequest.setAttribute("pools", list); } private void renderEdit(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { if (data.abstractName == null || data.abstractName.equals("")) { DatabaseDriver info = getDatabaseInfo(renderRequest, data); loadDriverJARList(renderRequest, info); } if (!data.isGeneric()) { ResourceAdapterParams params = getRARConfiguration(renderRequest, data.getRarPath(), data.getAdapterDisplayName(), renderRequest.getParameter("adapterAbstractName")); data.adapterDisplayName = params.getDisplayName(); data.adapterDescription = params.getDescription(); data.adapterRarPath = params.getRarPath(); Map<String, ConfigParam> map = new HashMap<String, ConfigParam>(); boolean more = false; for (int i = 0; i < params.getConfigParams().length; i++) { ConfigParam param = params.getConfigParams()[i]; if (!data.properties.containsKey("property-" + param.getName())) { data.properties.put("property-" + param.getName(), param.getDefaultValue()); more = true; } map.put("property-" + param.getName(), param); } if (more) { data.loadPropertyNames(); } data.sort(); renderRequest.setAttribute("ConfigParams", map); } editView.include(renderRequest, renderResponse); } private void renderSelectRDBMS(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("databases", getAllDrivers(renderRequest)); selectRDBMSView.include(renderRequest, renderResponse); } private void renderDownload(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { renderRequest.setAttribute("drivers", getDriverInfo(renderRequest)); downloadView.include(renderRequest, renderResponse); } private void renderDownloadStatus(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { downloadStatusView.include(renderRequest, renderResponse); } private void renderBasicParams(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { DatabaseDriver info = getDatabaseInfo(renderRequest, data); loadDriverJARList(renderRequest, info); // Make sure all properties available for the DB are listed if (info != null) { for (String param : info.getURLParameters()) { final String key = "urlproperty-" + param; if (!data.getUrlProperties().containsKey(key)) { data.getUrlProperties().put(key, param.equalsIgnoreCase("port") && info.getDefaultPort() > 0 ? info.getDefaultPort() : null); } } } // Pass on errors renderRequest.setAttribute("driverError", renderRequest.getParameter("driverError")); basicParamsView.include(renderRequest, renderResponse); } private void loadDriverJARList(RenderRequest renderRequest, DatabaseDriver info) { // List the available JARs List<String> list = new ArrayList<String>(); ListableRepository[] repos = PortletManager.getCurrentServer(renderRequest).getRepositories(); Set<Artifact> dependencyFilters = info == null? null : info.getDependencyFilters(); for (ListableRepository repo : repos) { SortedSet<Artifact> artifacts = repo.list(); for (Artifact artifact : artifacts) { if (dependencyFilters != null) { for (Artifact filter: dependencyFilters) { // It is too strict if using artifact.matches(filter) if (filter.getGroupId() != null && artifact.getGroupId().indexOf(filter.getGroupId()) == -1) continue; if (filter.getArtifactId() != null && artifact.getArtifactId().indexOf(filter.getArtifactId()) == -1) continue; if (filter.getVersion() != null && !artifact.getVersion().equals(filter.getVersion())) continue; if (filter.getType() != null && !artifact.getType().equals(filter.getType())) continue; list.add(artifact.toString()); } } else if (INCLUDE_ARTIFACTIDS.contains(artifact.getArtifactId()) || !EXCLUDE_GROUPIDS.contains(artifact.getGroupId())) { list.add(artifact.toString()); } } } Collections.sort(list); renderRequest.setAttribute("availableJars", list); } private void renderConfirmURL(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { confirmURLView.include(renderRequest, renderResponse); } private void renderTestConnection(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("targetDBInfo", renderRequest.getParameter("targetDBInfo")); renderRequest.setAttribute("connected", Boolean.valueOf(renderRequest.getParameter("connected"))); testConnectionView.include(renderRequest, renderResponse); } private void renderPlan(RenderRequest renderRequest, RenderResponse renderResponse, PoolData data) throws IOException, PortletException { // Pass on results renderRequest.setAttribute("deploymentPlan", renderRequest.getPortletSession().getAttribute("deploymentPlan")); // Digest the RAR URI String path = PortletManager.getRepositoryEntry(renderRequest, data.getRarPath()).getPath(); String base = PortletManager.getCurrentServer(renderRequest).getServerInfo().getCurrentBaseDirectory(); if (base != null && path.startsWith(base)) { path = path.substring(base.length()); if (path.startsWith("/")) { path = path.substring(1); } } else { int pos = path.lastIndexOf('/'); path = path.substring(pos + 1); } renderRequest.setAttribute("rarRelativePath", path); planView.include(renderRequest, renderResponse); } private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException { Class driverClass = attemptDriverLoad(request, data); Driver driver = (Driver) driverClass.newInstance(); if (driver.acceptsURL(data.url)) { Properties props = new Properties(); if (data.user != null) { props.put("user", data.user); } if (data.password != null) { props.put("password", data.password); } Connection con = null; try { con = driver.connect(data.url, props); final DatabaseMetaData metaData = con.getMetaData(); return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion(); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { //ignore } } } } else throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url); } private void delete(PortletRequest request, ActionResponse response, PoolData data) { // check to make sure the abstract name does not begin with 'org.apache.geronimo.configs' // if it does not - then delete it -- otherwise it is a system database if (data.getAbstractName() != null) { boolean isSystemDatabasePool = (data.getAbstractName().indexOf("org.apache.geronimo.configs") == 0); if (!isSystemDatabasePool) { DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { // retrieve all running modules TargetModuleID[] runningIds = mgr.getRunningModules(ModuleType.RAR, mgr.getTargets()); // index of module to keep int index = -1; // only keep module id that is associated with selected DB pool for (int i = 0; i < runningIds.length; i++) { if (data.getAbstractName().contains(runningIds[i].getModuleID())) { index = i; break; } } TargetModuleID[] ids = {runningIds[index]}; // undeploy the db pool ProgressObject po = mgr.undeploy(ids); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { log.info("Undeployment completed successfully!"); } } catch (Exception e) { log.error("Undeployment unsuccessful!"); } finally { if (mgr != null) mgr.release(); } } } } private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) { ImportStatus status = getImportStatus(request); if (data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool data.name = data.name.replaceAll("\\s", ""); DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager(); try { String rarPath = data.getRarPath(); File rarFile = getRAR(request, rarPath); //URI uri = getRAR(request, data.getRarPath()).toURI(); ConnectorDeployable deployable = new ConnectorDeployable(PortletManager.getRepositoryEntryBundle(request, rarPath)); DeploymentConfiguration config = mgr.createConfiguration(deployable); final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot(); Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot); ConnectorDCB connector = (ConnectorDCB) root.getDConfigBean( ddBeanRoot.getChildBean(root.getXpaths()[0])[0]); EnvironmentData environment = new EnvironmentData(); connector.setEnvironment(environment); org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact(); environment.setConfigId(configId); configId.setGroupId("console.dbpool"); configId.setVersion("1.0"); configId.setType("car"); String artifactId = data.name; // simply replace / with _ if / exists within the artifactId // this is needed because we don't allow / within the artifactId artifactId = artifactId.replace('/', '_'); // Let's check whether the artifact exists ConfigurationManager configurationManager = ConfigurationUtil.getConfigurationManager(PortletManager.getKernel()); if (configurationManager.isInstalled(new Artifact(configId.getGroupId(), artifactId, configId.getVersion(), configId.getType()))) { artifactId = artifactId + "_" + new Random(System.currentTimeMillis()).nextInt(99); } configId.setArtifactId(artifactId); String[] jars = data.getJars(); int length = jars[jars.length - 1].length() == 0 ? jars.length - 1 : jars.length; org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length]; for (int i = 0; i < dependencies.length; i++) { dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact(); } environment.setDependencies(dependencies); for (int i = 0; i < dependencies.length; i++) { Artifact tmp = Artifact.create(jars[i]); dependencies[i].setGroupId(tmp.getGroupId()); dependencies[i].setArtifactId(tmp.getArtifactId()); dependencies[i].setVersion(tmp.getVersion().toString()); dependencies[i].setType(tmp.getType()); } ResourceAdapter adapter = connector.getResourceAdapter()[0]; ConnectionDefinition definition = new ConnectionDefinition(); adapter.setConnectionDefinition(new ConnectionDefinition[]{definition}); definition.setConnectionFactoryInterface("javax.sql.DataSource"); ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance(); definition.setConnectionInstance(new ConnectionDefinitionInstance[]{instance}); instance.setName(data.getName()); ConfigPropertySetting[] settings = instance.getConfigPropertySetting(); if (data.isGeneric()) { // it's a generic TranQL JDBC pool for (ConfigPropertySetting setting : settings) { if (setting.getName().equals("UserName")) { setting.setValue(data.user); } else if (setting.getName().equals("Password")) { setting.setValue(data.password); } else if (setting.getName().equals("ConnectionURL")) { setting.setValue(data.url); } else if (setting.getName().equals("Driver")) { setting.setValue(data.driverClass); } } } else { // it's an XA driver or non-TranQL RA for (ConfigPropertySetting setting : settings) { String value = data.properties.get("property-" + setting.getName()); setting.setValue(value == null ? "" : value); } } ConnectionManager manager = instance.getConnectionManager(); if(XA.equals(data.transactionType)){ manager.setTransactionXA(true); } else if (NONE.equals(data.transactionType)){ manager.setTransactionNone(true); } else { manager.setTransactionLocal(true); } SinglePool pool = new SinglePool(); manager.setPoolSingle(pool); pool.setMatchOne(true); // Max Size needs to be set before the minimum. This is because // the connection manager will constrain the minimum based on the // current maximum value in the pool. We might consider adding a // setPoolConstraints method to allow specifying both at the same time. if (data.maxSize != null && !data.maxSize.equals("")) { pool.setMaxSize(new Integer(data.maxSize)); } if (data.minSize != null && !data.minSize.equals("")) { pool.setMinSize(new Integer(data.minSize)); } if (data.blockingTimeout != null && !data.blockingTimeout.equals("")) { pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout)); } if (data.idleTimeout != null && !data.idleTimeout.equals("")) { pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout)); } if (planOnly) { ByteArrayOutputStream out = new ByteArrayOutputStream(); config.save(out); out.close(); return new String(out.toByteArray(), "US-ASCII"); } else { File tempFile = File.createTempFile("console-deployment", ".xml"); tempFile.deleteOnExit(); log.debug("Writing database pool deployment plan to " + tempFile.getAbsolutePath()); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile)); config.save(out); out.flush(); out.close(); Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] {targets[0]}; ProgressObject po = mgr.distribute(targets, rarFile, tempFile); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { TargetModuleID[] ids = po.getResultTargetModuleIDs(); po = mgr.start(ids); waitForProgress(po); if (po.getDeploymentStatus().isCompleted()) { ids = po.getResultTargetModuleIDs(); if (status != null) { status.getCurrentPool().setName(data.getName()); status.getCurrentPool().setConfigurationName(ids[0].getModuleID()); status.getCurrentPool().setFinished(true); response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } log.info("Deployment completed successfully!"); } } else if (po.getDeploymentStatus().isFailed()) { data.deployError = "Unable to deploy: " + data.name; response.setRenderParameter(MODE_KEY, EDIT_MODE); log.info("Deployment Failed!"); } } } catch (Exception e) { log.error("Unable to save connection pool", e); } finally { if (mgr != null) mgr.release(); } } else { // We're saving updates to an existing pool if (planOnly) { throw new UnsupportedOperationException("Can't update a plan for an existing deployment"); } try { JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager.getManagedBean( request, new AbstractName(URI.create(data.getAbstractName()))); if (data.isGeneric()) { factory.setConfigProperty("ConnectionURL", data.getUrl()); factory.setConfigProperty("UserName", data.getUser()); factory.setConfigProperty("Password", data.getPassword()); } else { for (Map.Entry<String, String> entry : data.getProperties().entrySet()) { factory.setConfigProperty(entry.getKey().substring("property-".length()), entry.getValue()); } } //todo: push the lookup into ManagementHelper /* PoolingAttributes pool = (PoolingAttributes) factory.getConnectionManagerContainer(); pool.setPartitionMinSize( data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize)); pool.setPartitionMaxSize( data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize)); pool.setBlockingTimeoutMilliseconds( data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000 : Integer.parseInt( data.blockingTimeout)); pool.setIdleTimeoutMinutes( data.idleTimeout == null || data.idleTimeout.equals("") ? 15 : Integer.parseInt( data.idleTimeout)); */ } catch (Exception e) { log.error("Unable to save connection pool", e); } } return null; } private static void waitForProgress(ProgressObject po) { while (po.getDeploymentStatus().isRunning()) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private static ImportStatus getImportStatus(PortletRequest request) { return (ImportStatus) request.getPortletSession(true).getAttribute("ImportStatus"); } private static File getRAR(PortletRequest request, String rarPath) { org.apache.geronimo.kernel.repository.Artifact artifact = org.apache.geronimo.kernel.repository.Artifact.create( rarPath); ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories(); for (ListableRepository repo : repos) { // if the artifact is not fully resolved then try to resolve it if (!artifact.isResolved()) { SortedSet results = repo.list(artifact); if (!results.isEmpty()) { artifact = (Artifact) results.first(); } else { continue; } } File url = repo.getLocation(artifact); if (url != null) { if (url.exists() && url.canRead() && !url.isDirectory()) { return url; } } } return null; } /** * WARNING: This method relies on having access to the same repository * URLs as the server uses. * * @param request portlet request * @param data info about jars to include * @return driver class */ private static Class attemptDriverLoad(PortletRequest request, PoolData data) { List<URL> list = new ArrayList<URL>(); try { String[] jars = data.getJars(); if (jars == null) { log.error("Driver load failed since no jar files were selected."); return null; } ListableRepository[] repos = PortletManager.getCurrentServer(request).getRepositories(); for (String jar : jars) { Artifact artifact = Artifact.create( jar); for (ListableRepository repo : repos) { File url = repo.getLocation(artifact); if (url != null) { list.add(url.toURI().toURL()); } } } URLClassLoader loader = new URLClassLoader(list.toArray(new URL[list.size()]), DatabasePoolPortlet.class.getClassLoader()); try { return loader.loadClass(data.driverClass); } catch (ClassNotFoundException e) { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } private static String populateURL(String url, List<String> keys, Map properties) { for (String key : keys) { String value = (String) properties.get("urlproperty-" + key); if (value == null || value.equals("")) { int begin = url.indexOf("{" + key + "}"); int end = begin + key.length() + 2; for (int j = begin - 1; j >= 0; j--) { char c = url.charAt(j); if (c == ';' || c == ':') { begin = j; break; } else if (c == '/') { if (url.length() > end && url.charAt(end) == '/') { begin = j; // Don't leave // if foo is null for /<foo>/ } break; } } url = url.substring(0, begin) + url.substring(end); } else { if (value.indexOf('\\') != -1 || value.indexOf('$') != -1) { // value contains backslash or dollar sign and needs preprocessing for replaceAll to work properly StringBuilder temp = new StringBuilder(); char[] valueChars = value.toCharArray(); for (char valueChar : valueChars) { if (valueChar == '\\' || valueChar == '$') { temp.append('\\'); } temp.append(valueChar); } value = temp.toString(); } url = url.replaceAll("\\{" + key + "\\}", value); } } return url; } private static DatabaseDriver[] getAllDrivers(PortletRequest request) { DatabaseDriver[] result = (DatabaseDriver[]) PortletManager.getGBeansImplementing(request, DatabaseDriver.class); Arrays.sort(result, new Comparator<DatabaseDriver>() { public int compare(DatabaseDriver o1, DatabaseDriver o2) { String name1 = o1.getName(); String name2 = o2.getName(); if (name1.equals("Other")) name1 = "zzzOther"; if (name2.equals("Other")) name2 = "zzzOther"; return name1.compareTo(name2); } }); return result; } private static DatabaseDriver getDatabaseInfo(PortletRequest request, PoolData data) { DatabaseDriver info = null; DatabaseDriver[] all = getAllDrivers(request); for (DatabaseDriver next : all) { if (next.getName().equals(data.getDbtype())) { info = next; break; } } return info; } private static DatabaseDriver getDatabaseInfoFromDriver(PortletRequest request, PoolData data) { DatabaseDriver info = null; DatabaseDriver[] all = getAllDrivers(request); for (DatabaseDriver next : all) { if (next.getDriverClassName() != null && next.getDriverClassName().equals(data.getDriverClass())) { info = next; break; } } return info; } public static class PoolData implements Serializable { private static final long serialVersionUID = 1L; private String name; private String dbtype; private String user; private String password; private Map<String, String> properties = new LinkedHashMap<String, String>(); // Configuration for non-Generic drivers private Map<String, Object> urlProperties = new HashMap<String, Object>(); // URL substitution for Generic drivers private Map<String, String> propertyNames; //todo: store these in the ConfigParam instead private String driverClass; private String url; private String urlPrototype; private String[] jars; private String minSize; private String maxSize; private String blockingTimeout; private String idleTimeout; private String abstractName; private String adapterDisplayName; private String adapterDescription; private String adapterRarPath; private String rarPath; private String transactionType; private String importSource; private Map<String, String> abstractNameMap; // generated as needed, don't need to read/write it private String deployError; public void load(PortletRequest request) { name = request.getParameter("name"); if (name != null && name.equals("")) name = null; driverClass = request.getParameter("driverClass"); if (driverClass != null && driverClass.equals("")) driverClass = null; dbtype = request.getParameter("dbtype"); if (dbtype != null && dbtype.equals("")) dbtype = null; user = request.getParameter("user"); if (user != null && user.equals("")) user = null; password = request.getParameter("password"); if (password != null && password.equals("")) password = null; url = request.getParameter("url"); if (url != null && url.equals("")) { url = null; } else if (url != null && url.startsWith("URLENCODED")) { try { url = URLDecoder.decode(url.substring(10), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to decode URL", e); } catch (IllegalArgumentException e) { // not encoded after all?? url = url.substring(10); } } urlPrototype = request.getParameter("urlPrototype"); if (urlPrototype != null && urlPrototype.equals("")) urlPrototype = null; jars = request.getParameterValues("jars"); minSize = request.getParameter("minSize"); if (minSize != null && minSize.equals("")) minSize = null; maxSize = request.getParameter("maxSize"); if (maxSize != null && maxSize.equals("")) maxSize = null; blockingTimeout = request.getParameter("blockingTimeout"); if (blockingTimeout != null && blockingTimeout.equals("")) blockingTimeout = null; idleTimeout = request.getParameter("idleTimeout"); if (idleTimeout != null && idleTimeout.equals("")) idleTimeout = null; abstractName = request.getParameter("abstractName"); if (abstractName != null && abstractName.equals("")) abstractName = null; adapterDisplayName = request.getParameter("adapterDisplayName"); if (adapterDisplayName != null && adapterDisplayName.equals("")) adapterDisplayName = null; adapterDescription = request.getParameter("adapterDescription"); if (adapterDescription != null && adapterDescription.equals("")) adapterDescription = null; rarPath = request.getParameter("rarPath"); if (rarPath != null && rarPath.equals("")) rarPath = null; importSource = request.getParameter("importSource"); if (importSource != null && importSource.equals("")) importSource = null; transactionType = request.getParameter("transactionType"); if (transactionType != null && "".equals(transactionType)) { if (dbtype != null && dbtype.endsWith("XA")) { transactionType = XA; } else { transactionType = LOCAL; } } Map map = request.getParameterMap(); propertyNames = new HashMap<String, String>(); for (Object o : map.keySet()) { String key = (String) o; if (key.startsWith("urlproperty-")) { urlProperties.put(key, request.getParameter(key)); } else if (key.startsWith("property-")) { properties.put(key, request.getParameter(key)); propertyNames.put(key, getPropertyName(key)); } } sort(); deployError = request.getParameter("deployError"); if (deployError != null && deployError.equals("")) deployError = null; } public void loadPropertyNames() { propertyNames = new HashMap<String, String>(); for (String key : properties.keySet()) { propertyNames.put(key, getPropertyName(key)); } } private static String getPropertyName(String key) { int pos = key.indexOf('-'); key = Character.toUpperCase(key.charAt(pos + 1)) + key.substring(pos + 2); StringBuilder buf = new StringBuilder(); pos = 0; for (int i = 1; i < key.length(); i++) { if(key.charAt(i)=='_') { buf.append(key.substring(pos, i)).append(" "); pos = i+1; } else{ if (Character.isUpperCase(key.charAt(i))) { if (Character.isUpperCase(key.charAt(i - 1)) || key.charAt(i-1)=='_') { // ongoing capitalized word } else { // start of a new word buf.append(key.substring(pos, i)).append(" "); pos = i; } } else { if (Character.isUpperCase( key.charAt(i - 1)) && i - pos > 1) { // first lower-case after a series of caps buf.append(key.substring(pos, i - 1)).append(" "); pos = i - 1; } } } } buf.append(key.substring(pos)); return buf.toString(); } public void store(ActionResponse response) { if (name != null) response.setRenderParameter("name", name); if (dbtype != null) response.setRenderParameter("dbtype", dbtype); if (driverClass != null) response.setRenderParameter("driverClass", driverClass); if (user != null) response.setRenderParameter("user", user); if (password != null) response.setRenderParameter("password", password); if (url != null) { // attempt to work around Pluto/Tomcat error with ; in a stored value try { response.setRenderParameter("url", "URLENCODED" + URLEncoder.encode(url, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unable to encode URL", e); } } if (urlPrototype != null) response.setRenderParameter("urlPrototype", urlPrototype); if (jars != null) response.setRenderParameter("jars", jars); if (minSize != null) response.setRenderParameter("minSize", minSize); if (maxSize != null) response.setRenderParameter("maxSize", maxSize); if (blockingTimeout != null) response.setRenderParameter("blockingTimeout", blockingTimeout); if (idleTimeout != null) response.setRenderParameter("idleTimeout", idleTimeout); if (abstractName != null) response.setRenderParameter("abstractName", abstractName); if (adapterDisplayName != null) response.setRenderParameter("adapterDisplayName", adapterDisplayName); if (adapterDescription != null) response.setRenderParameter("adapterDescription", adapterDescription); if (importSource != null) response.setRenderParameter("importSource", importSource); if (rarPath != null) response.setRenderParameter("rarPath", rarPath); if (transactionType != null) response.setRenderParameter("transactionType", transactionType); for (Map.Entry<String, Object> entry : urlProperties.entrySet()) { if (entry.getValue() != null) { response.setRenderParameter(entry.getKey(), entry.getValue().toString()); } } for (Map.Entry<String, String> entry : properties.entrySet()) { if (entry.getValue() != null) { response.setRenderParameter(entry.getKey(), entry.getValue()); } } if (deployError != null) response.setRenderParameter("deployError", deployError); } public void sort() { Map<String, String> sortedProperties = new LinkedHashMap<String, String>(); for (String propertyName : ORDERED_PROPERTY_NAMES) { if (properties.containsKey(propertyName)) { sortedProperties.put(propertyName, properties.get(propertyName)); properties.remove(propertyName); } } sortedProperties.putAll(properties); properties = sortedProperties; } public String getName() { return name; } public String getDbtype() { return dbtype; } public String getUser() { return user; } public String getPassword() { return password; } public Map<String, String> getProperties() { return properties; } public Map<String, String> getPropertyNames() { return propertyNames; } public Map<String, Object> getUrlProperties() { return urlProperties; } public String getUrl() { return url; } public String[] getJars() { return jars; } public String getMinSize() { return minSize; } public String getMaxSize() { return maxSize; } public String getBlockingTimeout() { return blockingTimeout; } public String getIdleTimeout() { return idleTimeout; } public String getDriverClass() { return driverClass; } public String getUrlPrototype() { return urlPrototype; } public String getAbstractName() { return abstractName; } public String getAdapterDisplayName() { return adapterDisplayName; } public String getAdapterDescription() { return adapterDescription; } public String getAdapterRarPath() { return adapterRarPath; } public String getRarPath() { return rarPath; } public boolean isGeneric() { //todo: is there any better way to tell? return adapterDisplayName == null || adapterDisplayName.equals("TranQL Generic JDBC Resource Adapter"); } public String getImportSource() { return importSource; } public Map<String, String> getAbstractNameMap() { if (abstractName == null) return Collections.emptyMap(); if (abstractNameMap != null) return abstractNameMap; AbstractName name = new AbstractName(URI.create(abstractName)); abstractNameMap = new HashMap<String, String>(name.getName()); abstractNameMap.put("domain", name.getObjectName().getDomain()); abstractNameMap.put("groupId", name.getArtifact().getGroupId()); abstractNameMap.put("artifactId", name.getArtifact().getArtifactId()); abstractNameMap.put("type", name.getArtifact().getType()); abstractNameMap.put("version", name.getArtifact().getVersion().toString()); return abstractNameMap; } public String getDeployError() { return deployError; } public String getTransactionType() { return transactionType; } public void setTransactionType(String transactionType) { this.transactionType = transactionType; } } public static class ConnectionPool implements Serializable, Comparable { private static final long serialVersionUID = 1L; private final String adapterAbstractName; private final String factoryAbstractName; private final String name; private final String parentName; private final int state; public ConnectionPool(AbstractName adapterAbstractName, AbstractName factoryAbstractName, String name, int state) { this.adapterAbstractName = adapterAbstractName.toURI().toString(); String parent = (String) adapterAbstractName.getName().get(NameFactory.J2EE_APPLICATION); if (parent != null && parent.equals("null")) { parent = null; } parentName = parent; this.factoryAbstractName = factoryAbstractName.toURI().toString(); this.name = name; this.state = state; } public String getAdapterAbstractName() { return adapterAbstractName; } public String getFactoryAbstractName() { return factoryAbstractName; } public String getName() { return name; } public String getParentName() { return parentName; } public int getState() { return state; } public String getStateName() { return State.toString(state); } public int compareTo(Object o) { final ConnectionPool pool = (ConnectionPool) o; int names = name.compareTo(pool.name); if (parentName == null) { if (pool.parentName == null) { return names; } else { return -1; } } else { if (pool.parentName == null) { return 1; } else { int test = parentName.compareTo(pool.parentName); if (test != 0) { return test; } else { return names; } } } } } public static class ResourceAdapterParams { private String displayName; private String description; private String rarPath; private ConfigParam[] configParams; public ResourceAdapterParams(String displayName, String description, String rarPath, ConfigParam[] configParams) { this.displayName = displayName; this.description = description; this.rarPath = rarPath; this.configParams = configParams; } public String getDisplayName() { return displayName; } public String getDescription() { return description; } public String getRarPath() { return rarPath; } public ConfigParam[] getConfigParams() { return configParams; } } public static class ConfigParam { private String name; private String type; private String description; private String defaultValue; public ConfigParam(String name, String type, String description, String defaultValue) { this.name = name; this.type = type; this.description = description; this.defaultValue = defaultValue; } public String getName() { return name; } public String getType() { return type; } public String getDescription() { return description; } public String getDefaultValue() { return defaultValue; } } }
GERONIMO-6108 Some labels could not display correctly in admin console's DBWizard page (Thanks Xiao Yi for the patch) git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@1156067 13f79535-47bb-0310-9956-ffa450edef68
plugins/system-database/sysdb-portlets/src/main/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java
GERONIMO-6108 Some labels could not display correctly in admin console's DBWizard page (Thanks Xiao Yi for the patch)
<ide><path>lugins/system-database/sysdb-portlets/src/main/java/org/apache/geronimo/console/databasemanager/wizard/DatabasePoolPortlet.java <ide> rarPathMap.put("TranQL XA Resource Adapter for DB2", "tranql-connector-db2-xa"); <ide> rarPathMap.put("TranQL Client Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-client-local"); <ide> rarPathMap.put("TranQL Client XA Resource Adapter for Apache Derby", "tranql-connector-derby-client-xa"); <del>// rarPathMap.put("TranQL Embedded Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); <del>// rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-xa"); <del> rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); <add> rarPathMap.put("TranQL Embedded Local Transaction Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); <add> rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-xa"); <add>// rarPathMap.put("TranQL Embedded XA Resource Adapter for Apache Derby", "tranql-connector-derby-embed-local"); <ide> rarPathMap.put("TranQL XA Resource Adapter for Informix", "tranql-connector-informix-xa"); <ide> rarPathMap.put("TranQL Client Local Transaction Resource Adapter for MySQL", "tranql-connector-mysql-local"); <ide> rarPathMap.put("TranQL Client XA Resource Adapter for MySQL", "tranql-connector-mysql-xa");
Java
apache-2.0
4d0a8a5c7e0cd5dd152b46383d314917fdfa5e06
0
chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq,chirino/activemq
/** * 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.transport; import java.io.IOException; import java.util.Timer; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.command.KeepAliveInfo; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.thread.SchedulerTimerTask; import org.apache.activemq.wireformat.WireFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Used to make sure that commands are arriving periodically from the peer of * the transport. * * @version $Revision$ */ public class InactivityMonitor extends TransportFilter { private static final Log LOG = LogFactory.getLog(InactivityMonitor.class); private static final ThreadPoolExecutor ASYNC_TASKS; private static int CHECKER_COUNTER; private static Timer READ_CHECK_TIMER; private static Timer WRITE_CHECK_TIMER; private WireFormatInfo localWireFormatInfo; private WireFormatInfo remoteWireFormatInfo; private final AtomicBoolean monitorStarted = new AtomicBoolean(false); private final AtomicBoolean commandSent = new AtomicBoolean(false); private final AtomicBoolean inSend = new AtomicBoolean(false); private final AtomicBoolean failed = new AtomicBoolean(false); private final AtomicBoolean commandReceived = new AtomicBoolean(true); private final AtomicBoolean inReceive = new AtomicBoolean(false); private final AtomicInteger lastReceiveCounter = new AtomicInteger(0); private SchedulerTimerTask writeCheckerTask; private SchedulerTimerTask readCheckerTask; private boolean ignoreRemoteWireFormat = false; private long readCheckTime; private long writeCheckTime; private long initialDelayTime; private boolean keepAliveResponseRequired; private WireFormat wireFormat; private final Runnable readChecker = new Runnable() { long lastRunTime; public void run() { long now = System.currentTimeMillis(); long elapsed = (now-lastRunTime); if( lastRunTime != 0 && LOG.isDebugEnabled() ) { LOG.debug(""+elapsed+" ms elapsed since last read check."); } // Perhaps the timer executed a read check late.. and then executes // the next read check on time which causes the time elapsed between // read checks to be small.. // If less than 90% of the read check Time elapsed then abort this readcheck. if( !allowReadCheck(elapsed) ) { // FUNKY qdox bug does not allow me to inline this expression. LOG.debug("Aborting read check.. Not enough time elapsed since last read check."); return; } lastRunTime = now; readCheck(); } }; private boolean allowReadCheck(long elapsed) { return elapsed > (readCheckTime * 9 / 10); } private final Runnable writeChecker = new Runnable() { long lastRunTime; public void run() { long now = System.currentTimeMillis(); if( lastRunTime != 0 && LOG.isDebugEnabled() ) { LOG.debug(""+(now-lastRunTime)+" ms elapsed since last write check."); } lastRunTime = now; writeCheck(); } }; public InactivityMonitor(Transport next, WireFormat wireFormat) { super(next); this.wireFormat = wireFormat; } public void stop() throws Exception { stopMonitorThreads(); next.stop(); } final void writeCheck() { if (inSend.get()) { if (LOG.isTraceEnabled()) { LOG.trace("A send is in progress"); } return; } if (!commandSent.get()) { if (LOG.isTraceEnabled()) { LOG.trace("No message sent since last write check, sending a KeepAliveInfo"); } ASYNC_TASKS.execute(new Runnable() { public void run() { if (monitorStarted.get()) { try { KeepAliveInfo info = new KeepAliveInfo(); info.setResponseRequired(keepAliveResponseRequired); oneway(info); } catch (IOException e) { onException(e); } } }; }); } else { if (LOG.isTraceEnabled()) { LOG.trace("Message sent since last write check, resetting flag"); } } commandSent.set(false); } final void readCheck() { int currentCounter = next.getReceiveCounter(); int previousCounter = lastReceiveCounter.getAndSet(currentCounter); if (inReceive.get() || currentCounter!=previousCounter ) { if (LOG.isTraceEnabled()) { LOG.trace("A receive is in progress"); } return; } if (!commandReceived.get()) { if (LOG.isDebugEnabled()) { LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); } ASYNC_TASKS.execute(new Runnable() { public void run() { onException(new InactivityIOException("Channel was inactive for too (>" + readCheckTime + ") long: "+next.getRemoteAddress())); }; }); } else { if (LOG.isTraceEnabled()) { LOG.trace("Message received since last read check, resetting flag: "); } } commandReceived.set(false); } public void onCommand(Object command) { commandReceived.set(true); inReceive.set(true); try { if (command.getClass() == KeepAliveInfo.class) { KeepAliveInfo info = (KeepAliveInfo) command; if (info.isResponseRequired()) { try { info.setResponseRequired(false); oneway(info); } catch (IOException e) { onException(e); } } } else { if (command.getClass() == WireFormatInfo.class) { synchronized (this) { IOException error = null; remoteWireFormatInfo = (WireFormatInfo) command; try { startMonitorThreads(); } catch (IOException e) { error = e; } if (error != null) { onException(error); } } } synchronized (readChecker) { transportListener.onCommand(command); } } } finally { inReceive.set(false); } } public void oneway(Object o) throws IOException { // Disable inactivity monitoring while processing a command. //synchronize this method - its not synchronized //further down the transport stack and gets called by more //than one thread by this class synchronized(inSend) { inSend.set(true); try { if( failed.get() ) { throw new InactivityIOException("Channel was inactive for too long: "+next.getRemoteAddress()); } if (o.getClass() == WireFormatInfo.class) { synchronized (this) { localWireFormatInfo = (WireFormatInfo)o; startMonitorThreads(); } } next.oneway(o); } finally { commandSent.set(true); inSend.set(false); } } } public void onException(IOException error) { if (failed.compareAndSet(false, true)) { stopMonitorThreads(); transportListener.onException(error); } } public void setKeepAliveResponseRequired(boolean val) { keepAliveResponseRequired = val; } public void setIgnoreRemoteWireFormat(boolean val) { ignoreRemoteWireFormat = val; } private synchronized void startMonitorThreads() throws IOException { if (monitorStarted.get()) { return; } if (localWireFormatInfo == null) { return; } if (remoteWireFormatInfo == null) { return; } if (!ignoreRemoteWireFormat) { readCheckTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration()); initialDelayTime = Math.min(localWireFormatInfo.getMaxInactivityDurationInitalDelay(), remoteWireFormatInfo.getMaxInactivityDurationInitalDelay()); } else { readCheckTime = localWireFormatInfo.getMaxInactivityDuration(); initialDelayTime = localWireFormatInfo.getMaxInactivityDurationInitalDelay(); } if (readCheckTime > 0) { monitorStarted.set(true); writeCheckerTask = new SchedulerTimerTask(writeChecker); readCheckerTask = new SchedulerTimerTask(readChecker); writeCheckTime = readCheckTime>3 ? readCheckTime/3 : readCheckTime; synchronized( InactivityMonitor.class ) { if( CHECKER_COUNTER == 0 ) { READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck",true); WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck",true); } CHECKER_COUNTER++; WRITE_CHECK_TIMER.scheduleAtFixedRate(writeCheckerTask, initialDelayTime,writeCheckTime); READ_CHECK_TIMER.scheduleAtFixedRate(readCheckerTask, initialDelayTime,readCheckTime); } } } /** * */ private synchronized void stopMonitorThreads() { if (monitorStarted.compareAndSet(true, false)) { readCheckerTask.cancel(); writeCheckerTask.cancel(); synchronized( InactivityMonitor.class ) { WRITE_CHECK_TIMER.purge(); READ_CHECK_TIMER.purge(); CHECKER_COUNTER--; if(CHECKER_COUNTER==0) { WRITE_CHECK_TIMER.cancel(); READ_CHECK_TIMER.cancel(); WRITE_CHECK_TIMER = null; READ_CHECK_TIMER = null; } } } } static { ASYNC_TASKS = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "InactivityMonitor Async Task: "+runnable); thread.setDaemon(true); return thread; } }); } }
activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java
/** * 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.transport; import java.io.IOException; import java.util.Timer; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.command.KeepAliveInfo; import org.apache.activemq.command.WireFormatInfo; import org.apache.activemq.thread.SchedulerTimerTask; import org.apache.activemq.wireformat.WireFormat; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Used to make sure that commands are arriving periodically from the peer of * the transport. * * @version $Revision$ */ public class InactivityMonitor extends TransportFilter { private static final Log LOG = LogFactory.getLog(InactivityMonitor.class); private static final ThreadPoolExecutor ASYNC_TASKS; private static int CHECKER_COUNTER; private static Timer READ_CHECK_TIMER; private static Timer WRITE_CHECK_TIMER; private WireFormatInfo localWireFormatInfo; private WireFormatInfo remoteWireFormatInfo; private final AtomicBoolean monitorStarted = new AtomicBoolean(false); private final AtomicBoolean commandSent = new AtomicBoolean(false); private final AtomicBoolean inSend = new AtomicBoolean(false); private final AtomicBoolean failed = new AtomicBoolean(false); private final AtomicBoolean commandReceived = new AtomicBoolean(true); private final AtomicBoolean inReceive = new AtomicBoolean(false); private final AtomicInteger lastReceiveCounter = new AtomicInteger(0); private SchedulerTimerTask writeCheckerTask; private SchedulerTimerTask readCheckerTask; private long readCheckTime; private long writeCheckTime; private long initialDelayTime; private boolean keepAliveResponseRequired; private WireFormat wireFormat; private final Runnable readChecker = new Runnable() { long lastRunTime; public void run() { long now = System.currentTimeMillis(); long elapsed = (now-lastRunTime); if( lastRunTime != 0 && LOG.isDebugEnabled() ) { LOG.debug(""+elapsed+" ms elapsed since last read check."); } // Perhaps the timer executed a read check late.. and then executes // the next read check on time which causes the time elapsed between // read checks to be small.. // If less than 90% of the read check Time elapsed then abort this readcheck. if( !allowReadCheck(elapsed) ) { // FUNKY qdox bug does not allow me to inline this expression. LOG.debug("Aborting read check.. Not enough time elapsed since last read check."); return; } lastRunTime = now; readCheck(); } }; private boolean allowReadCheck(long elapsed) { return elapsed > (readCheckTime * 9 / 10); } private final Runnable writeChecker = new Runnable() { long lastRunTime; public void run() { long now = System.currentTimeMillis(); if( lastRunTime != 0 && LOG.isDebugEnabled() ) { LOG.debug(""+(now-lastRunTime)+" ms elapsed since last write check."); } lastRunTime = now; writeCheck(); } }; public InactivityMonitor(Transport next, WireFormat wireFormat) { super(next); this.wireFormat = wireFormat; } public void stop() throws Exception { stopMonitorThreads(); next.stop(); } final void writeCheck() { if (inSend.get()) { if (LOG.isTraceEnabled()) { LOG.trace("A send is in progress"); } return; } if (!commandSent.get()) { if (LOG.isTraceEnabled()) { LOG.trace("No message sent since last write check, sending a KeepAliveInfo"); } ASYNC_TASKS.execute(new Runnable() { public void run() { if (monitorStarted.get()) { try { KeepAliveInfo info = new KeepAliveInfo(); info.setResponseRequired(keepAliveResponseRequired); oneway(info); } catch (IOException e) { onException(e); } } }; }); } else { if (LOG.isTraceEnabled()) { LOG.trace("Message sent since last write check, resetting flag"); } } commandSent.set(false); } final void readCheck() { int currentCounter = next.getReceiveCounter(); int previousCounter = lastReceiveCounter.getAndSet(currentCounter); if (inReceive.get() || currentCounter!=previousCounter ) { if (LOG.isTraceEnabled()) { LOG.trace("A receive is in progress"); } return; } if (!commandReceived.get()) { if (LOG.isDebugEnabled()) { LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); } ASYNC_TASKS.execute(new Runnable() { public void run() { onException(new InactivityIOException("Channel was inactive for too (>" + readCheckTime + ") long: "+next.getRemoteAddress())); }; }); } else { if (LOG.isTraceEnabled()) { LOG.trace("Message received since last read check, resetting flag: "); } } commandReceived.set(false); } public void onCommand(Object command) { commandReceived.set(true); inReceive.set(true); try { if (command.getClass() == KeepAliveInfo.class) { KeepAliveInfo info = (KeepAliveInfo) command; if (info.isResponseRequired()) { try { info.setResponseRequired(false); oneway(info); } catch (IOException e) { onException(e); } } } else { if (command.getClass() == WireFormatInfo.class) { synchronized (this) { IOException error = null; remoteWireFormatInfo = (WireFormatInfo) command; try { startMonitorThreads(); } catch (IOException e) { error = e; } if (error != null) { onException(error); } } } synchronized (readChecker) { transportListener.onCommand(command); } } } finally { inReceive.set(false); } } public void oneway(Object o) throws IOException { // Disable inactivity monitoring while processing a command. //synchronize this method - its not synchronized //further down the transport stack and gets called by more //than one thread by this class synchronized(inSend) { inSend.set(true); try { if( failed.get() ) { throw new InactivityIOException("Channel was inactive for too long: "+next.getRemoteAddress()); } if (o.getClass() == WireFormatInfo.class) { synchronized (this) { localWireFormatInfo = (WireFormatInfo)o; startMonitorThreads(); } } next.oneway(o); } finally { commandSent.set(true); inSend.set(false); } } } public void onException(IOException error) { if (failed.compareAndSet(false, true)) { stopMonitorThreads(); transportListener.onException(error); } } public void setKeepAliveResponseRequired(boolean val) { keepAliveResponseRequired = val; } private synchronized void startMonitorThreads() throws IOException { if (monitorStarted.get()) { return; } if (localWireFormatInfo == null) { return; } if (remoteWireFormatInfo == null) { return; } readCheckTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration()); initialDelayTime = Math.min(localWireFormatInfo.getMaxInactivityDurationInitalDelay(), remoteWireFormatInfo.getMaxInactivityDurationInitalDelay()); if (readCheckTime > 0) { monitorStarted.set(true); writeCheckerTask = new SchedulerTimerTask(writeChecker); readCheckerTask = new SchedulerTimerTask(readChecker); writeCheckTime = readCheckTime>3 ? readCheckTime/3 : readCheckTime; synchronized( InactivityMonitor.class ) { if( CHECKER_COUNTER == 0 ) { READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck",true); WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck",true); } CHECKER_COUNTER++; WRITE_CHECK_TIMER.scheduleAtFixedRate(writeCheckerTask, initialDelayTime,writeCheckTime); READ_CHECK_TIMER.scheduleAtFixedRate(readCheckerTask, initialDelayTime,readCheckTime); } } } /** * */ private synchronized void stopMonitorThreads() { if (monitorStarted.compareAndSet(true, false)) { readCheckerTask.cancel(); writeCheckerTask.cancel(); synchronized( InactivityMonitor.class ) { WRITE_CHECK_TIMER.purge(); READ_CHECK_TIMER.purge(); CHECKER_COUNTER--; if(CHECKER_COUNTER==0) { WRITE_CHECK_TIMER.cancel(); READ_CHECK_TIMER.cancel(); WRITE_CHECK_TIMER = null; READ_CHECK_TIMER = null; } } } } static { ASYNC_TASKS = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, "InactivityMonitor Async Task: "+runnable); thread.setDaemon(true); return thread; } }); } }
https://issues.apache.org/activemq/browse/AMQ-2196 Add option to ignore the values in the remote WireFormatInfo in case the user wants control over the Brokers inactivity timeouts. git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@905769 13f79535-47bb-0310-9956-ffa450edef68
activemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java
https://issues.apache.org/activemq/browse/AMQ-2196
<ide><path>ctivemq-core/src/main/java/org/apache/activemq/transport/InactivityMonitor.java <ide> /** <ide> * Used to make sure that commands are arriving periodically from the peer of <ide> * the transport. <del> * <add> * <ide> * @version $Revision$ <ide> */ <ide> public class InactivityMonitor extends TransportFilter { <ide> <ide> private static final Log LOG = LogFactory.getLog(InactivityMonitor.class); <ide> private static final ThreadPoolExecutor ASYNC_TASKS; <del> <add> <ide> private static int CHECKER_COUNTER; <ide> private static Timer READ_CHECK_TIMER; <ide> private static Timer WRITE_CHECK_TIMER; <del> <add> <ide> private WireFormatInfo localWireFormatInfo; <ide> private WireFormatInfo remoteWireFormatInfo; <ide> private final AtomicBoolean monitorStarted = new AtomicBoolean(false); <ide> private final AtomicBoolean commandReceived = new AtomicBoolean(true); <ide> private final AtomicBoolean inReceive = new AtomicBoolean(false); <ide> private final AtomicInteger lastReceiveCounter = new AtomicInteger(0); <del> <add> <ide> private SchedulerTimerTask writeCheckerTask; <ide> private SchedulerTimerTask readCheckerTask; <del> <add> <add> private boolean ignoreRemoteWireFormat = false; <ide> private long readCheckTime; <ide> private long writeCheckTime; <ide> private long initialDelayTime; <ide> private boolean keepAliveResponseRequired; <ide> private WireFormat wireFormat; <del> <add> <ide> private final Runnable readChecker = new Runnable() { <ide> long lastRunTime; <ide> public void run() { <ide> if( lastRunTime != 0 && LOG.isDebugEnabled() ) { <ide> LOG.debug(""+elapsed+" ms elapsed since last read check."); <ide> } <del> <add> <ide> // Perhaps the timer executed a read check late.. and then executes <ide> // the next read check on time which causes the time elapsed between <ide> // read checks to be small.. <del> <del> // If less than 90% of the read check Time elapsed then abort this readcheck. <add> <add> // If less than 90% of the read check Time elapsed then abort this readcheck. <ide> if( !allowReadCheck(elapsed) ) { // FUNKY qdox bug does not allow me to inline this expression. <ide> LOG.debug("Aborting read check.. Not enough time elapsed since last read check."); <ide> return; <ide> } <del> <add> <ide> lastRunTime = now; <ide> readCheck(); <ide> } <ide> }; <del> <add> <ide> private boolean allowReadCheck(long elapsed) { <ide> return elapsed > (readCheckTime * 9 / 10); <ide> } <ide> long now = System.currentTimeMillis(); <ide> if( lastRunTime != 0 && LOG.isDebugEnabled() ) { <ide> LOG.debug(""+(now-lastRunTime)+" ms elapsed since last write check."); <del> <del> } <del> lastRunTime = now; <add> <add> } <add> lastRunTime = now; <ide> writeCheck(); <ide> } <ide> }; <ide> } <ide> <ide> public void stop() throws Exception { <del> stopMonitorThreads(); <add> stopMonitorThreads(); <ide> next.stop(); <ide> } <ide> <ide> if (LOG.isDebugEnabled()) { <ide> LOG.debug("No message received since last read check for " + toString() + "! Throwing InactivityIOException."); <ide> } <del> ASYNC_TASKS.execute(new Runnable() { <add> ASYNC_TASKS.execute(new Runnable() { <ide> public void run() { <ide> onException(new InactivityIOException("Channel was inactive for too (>" + readCheckTime + ") long: "+next.getRemoteAddress())); <ide> }; <del> <add> <ide> }); <ide> } else { <ide> if (LOG.isTraceEnabled()) { <ide> } <ide> } <ide> } finally { <del> <add> <ide> inReceive.set(false); <ide> } <ide> } <ide> public void oneway(Object o) throws IOException { <ide> // Disable inactivity monitoring while processing a command. <ide> //synchronize this method - its not synchronized <del> //further down the transport stack and gets called by more <add> //further down the transport stack and gets called by more <ide> //than one thread by this class <ide> synchronized(inSend) { <ide> inSend.set(true); <ide> try { <del> <add> <ide> if( failed.get() ) { <ide> throw new InactivityIOException("Channel was inactive for too long: "+next.getRemoteAddress()); <ide> } <ide> stopMonitorThreads(); <ide> transportListener.onException(error); <ide> } <del> } <del> <add> } <add> <ide> public void setKeepAliveResponseRequired(boolean val) { <ide> keepAliveResponseRequired = val; <ide> } <ide> <add> public void setIgnoreRemoteWireFormat(boolean val) { <add> ignoreRemoteWireFormat = val; <add> } <add> <ide> private synchronized void startMonitorThreads() throws IOException { <ide> if (monitorStarted.get()) { <ide> return; <ide> return; <ide> } <ide> <del> readCheckTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration()); <del> initialDelayTime = Math.min(localWireFormatInfo.getMaxInactivityDurationInitalDelay(), remoteWireFormatInfo.getMaxInactivityDurationInitalDelay()); <add> if (!ignoreRemoteWireFormat) { <add> readCheckTime = Math.min(localWireFormatInfo.getMaxInactivityDuration(), remoteWireFormatInfo.getMaxInactivityDuration()); <add> initialDelayTime = Math.min(localWireFormatInfo.getMaxInactivityDurationInitalDelay(), remoteWireFormatInfo.getMaxInactivityDurationInitalDelay()); <add> } else { <add> readCheckTime = localWireFormatInfo.getMaxInactivityDuration(); <add> initialDelayTime = localWireFormatInfo.getMaxInactivityDurationInitalDelay(); <add> } <add> <ide> if (readCheckTime > 0) { <ide> monitorStarted.set(true); <ide> writeCheckerTask = new SchedulerTimerTask(writeChecker); <ide> readCheckerTask = new SchedulerTimerTask(readChecker); <ide> writeCheckTime = readCheckTime>3 ? readCheckTime/3 : readCheckTime; <ide> synchronized( InactivityMonitor.class ) { <del> if( CHECKER_COUNTER == 0 ) { <del> READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck",true); <del> WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck",true); <del> } <del> CHECKER_COUNTER++; <add> if( CHECKER_COUNTER == 0 ) { <add> READ_CHECK_TIMER = new Timer("InactivityMonitor ReadCheck",true); <add> WRITE_CHECK_TIMER = new Timer("InactivityMonitor WriteCheck",true); <add> } <add> CHECKER_COUNTER++; <ide> WRITE_CHECK_TIMER.scheduleAtFixedRate(writeCheckerTask, initialDelayTime,writeCheckTime); <ide> READ_CHECK_TIMER.scheduleAtFixedRate(readCheckerTask, initialDelayTime,readCheckTime); <ide> } <ide> readCheckerTask.cancel(); <ide> writeCheckerTask.cancel(); <ide> synchronized( InactivityMonitor.class ) { <del> WRITE_CHECK_TIMER.purge(); <del> READ_CHECK_TIMER.purge(); <del> CHECKER_COUNTER--; <del> if(CHECKER_COUNTER==0) { <del> WRITE_CHECK_TIMER.cancel(); <del> READ_CHECK_TIMER.cancel(); <del> WRITE_CHECK_TIMER = null; <del> READ_CHECK_TIMER = null; <del> } <del> } <del> } <del> } <del> <del> <add> WRITE_CHECK_TIMER.purge(); <add> READ_CHECK_TIMER.purge(); <add> CHECKER_COUNTER--; <add> if(CHECKER_COUNTER==0) { <add> WRITE_CHECK_TIMER.cancel(); <add> READ_CHECK_TIMER.cancel(); <add> WRITE_CHECK_TIMER = null; <add> READ_CHECK_TIMER = null; <add> } <add> } <add> } <add> } <add> <add> <ide> static { <ide> ASYNC_TASKS = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() { <ide> public Thread newThread(Runnable runnable) {
Java
apache-2.0
31d46d03bd29e9d29c2797f5e72735450a9bf45b
0
tsmgeek/traccar,ninioe/traccar,jssenyange/traccar,jon-stumpf/traccar,orcoliver/traccar,jon-stumpf/traccar,tananaev/traccar,jssenyange/traccar,jon-stumpf/traccar,ninioe/traccar,tananaev/traccar,orcoliver/traccar,jssenyange/traccar,orcoliver/traccar,tsmgeek/traccar,tananaev/traccar,tsmgeek/traccar,ninioe/traccar
/* * Copyright 2012 - 2017 Anton Tananaev ([email protected]) * * 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.traccar.protocol; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.helper.BitUtil; import org.traccar.helper.UnitsConverter; import org.traccar.model.Position; import java.net.SocketAddress; import java.nio.charset.StandardCharsets; import java.util.Date; public class AdmProtocolDecoder extends BaseProtocolDecoder { public AdmProtocolDecoder(AdmProtocol protocol) { super(protocol); } public static final int CMD_RESPONSE_SIZE = 0x84; public static final int MSG_IMEI = 0x03; public static final int MSG_PHOTO = 0x0A; public static final int MSG_ADM5 = 0x01; private Position decodeData(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf, int type) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } if (BitUtil.to(type, 2) == 0) { Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_VERSION_FW, buf.readUnsignedByte()); position.set(Position.KEY_INDEX, buf.readUnsignedShort()); int status = buf.readUnsignedShort(); position.set(Position.KEY_STATUS, status); position.setValid(!BitUtil.check(status, 5)); position.setLatitude(buf.readFloat()); position.setLongitude(buf.readFloat()); position.setCourse(buf.readUnsignedShort() * 0.1); position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort() * 0.1)); position.set(Position.KEY_ACCELERATION, buf.readUnsignedByte() * 0.1); position.setAltitude(buf.readUnsignedShort()); position.set(Position.KEY_HDOP, buf.readUnsignedByte() * 0.1); position.set(Position.KEY_SATELLITES, buf.readUnsignedByte() & 0x0f); position.setTime(new Date(buf.readUnsignedInt() * 1000)); position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.001); position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.001); if (BitUtil.check(type, 2)) { buf.skipBytes(2); // vib, vib_count int out = buf.readUnsignedByte(); for (int i = 0; i <= 3; ++i) { position.set(Position.PREFIX_OUT + (i + 1), BitUtil.check(out, i) ? 1 : 0); } buf.skipBytes(1); // in_alarm } if (BitUtil.check(type, 3)) { for (int i = 1; i <= 6; ++i) { position.set(Position.PREFIX_ADC + i, buf.readUnsignedShort() * 0.001); } } if (BitUtil.check(type, 4)) { for (int i = 1; i <= 2; ++i) { position.set(Position.PREFIX_COUNT + i, buf.readUnsignedInt()); } } if (BitUtil.check(type, 5)) { buf.skipBytes(6); // fuel level 0..2 for (int i = 1; i <= 3; ++i) { position.set(Position.PREFIX_TEMP + i, buf.readUnsignedByte()); } } if (BitUtil.check(type, 6)) { buf.skipBytes(buf.getUnsignedByte(buf.readerIndex())); } if (BitUtil.check(type, 7)) { position.set(Position.KEY_ODOMETER, buf.readUnsignedInt()); } return position; } return null; } private Position parseCommandResponse(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); position.set(Position.KEY_RESULT, buf.readBytes(129).toString(StandardCharsets.UTF_8)); return position; } @Override protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ChannelBuffer buf = (ChannelBuffer) msg; buf.readUnsignedShort(); // device id int size = buf.readUnsignedByte(); if (size != CMD_RESPONSE_SIZE) { int type = buf.readUnsignedByte(); if (type == MSG_IMEI) { getDeviceSession(channel, remoteAddress, buf.readBytes(15).toString(StandardCharsets.UTF_8)); } else { return decodeData(channel, remoteAddress, buf, type); } } else { return parseCommandResponse(channel, remoteAddress, buf); } return null; } }
src/org/traccar/protocol/AdmProtocolDecoder.java
/* * Copyright 2012 - 2017 Anton Tananaev ([email protected]) * * 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.traccar.protocol; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.helper.BitUtil; import org.traccar.helper.UnitsConverter; import org.traccar.model.Position; import java.net.SocketAddress; import java.nio.charset.StandardCharsets; import java.util.Date; public class AdmProtocolDecoder extends BaseProtocolDecoder { public AdmProtocolDecoder(AdmProtocol protocol) { super(protocol); } public static final int CMD_RESPONSE_SIZE = 0x84; public static final int MSG_IMEI = 0x03; public static final int MSG_PHOTO = 0x0A; public static final int MSG_ADM5 = 0x01; private Position parseData(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf, int type) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } if (BitUtil.to(type, 2) == 0) { Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.set(Position.KEY_VERSION_FW, buf.readUnsignedByte()); position.set(Position.KEY_INDEX, buf.readUnsignedShort()); int status = buf.readUnsignedShort(); position.set(Position.KEY_STATUS, status); position.setValid(!BitUtil.check(status, 5)); position.setLatitude(buf.readFloat()); position.setLongitude(buf.readFloat()); position.setCourse(buf.readUnsignedShort() * 0.1); position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort() * 0.1)); position.set(Position.KEY_ACCELERATION, buf.readUnsignedByte() * 0.1); position.setAltitude(buf.readUnsignedShort()); position.set(Position.KEY_HDOP, buf.readUnsignedByte() * 0.1); position.set(Position.KEY_SATELLITES, buf.readUnsignedByte() & 0x0f); position.setTime(new Date(buf.readUnsignedInt() * 1000)); position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.001); position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.001); if (BitUtil.check(type, 2)) { buf.skipBytes(2); // vib, vib_count int out = buf.readUnsignedByte(); for (int i = 0; i <= 3; ++i) { position.set(Position.PREFIX_OUT + (i + 1), BitUtil.check(out, i) ? 1 : 0); } buf.skipBytes(1); // in_alarm } if (BitUtil.check(type, 3)) { for (int i = 1; i <= 6; ++i) { position.set(Position.PREFIX_ADC + i, buf.readUnsignedShort() * 0.001); } } if (BitUtil.check(type, 4)) { for (int i = 1; i <= 2; ++i) { position.set(Position.PREFIX_COUNT + i, buf.readUnsignedInt()); } } if (BitUtil.check(type, 5)) { buf.skipBytes(6); // fuel level 0..2 for (int i = 1; i <= 3; ++i) { position.set(Position.PREFIX_TEMP + i, buf.readUnsignedByte()); } } if (BitUtil.check(type, 6)) { buf.skipBytes(buf.getUnsignedByte(buf.readerIndex())); } if (BitUtil.check(type, 7)) { position.set(Position.KEY_ODOMETER, buf.readUnsignedInt()); } return position; } return null; } private Position parseCommandResponse(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } Position position = new Position(); position.setProtocol(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); position.set(Position.KEY_RESULT, buf.readBytes(129).toString(StandardCharsets.UTF_8)); return position; } @Override protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { ChannelBuffer buf = (ChannelBuffer) msg; buf.readUnsignedShort(); // device id int size = buf.readUnsignedByte(); if (size != CMD_RESPONSE_SIZE) { int type = buf.readUnsignedByte(); if (type == MSG_IMEI) { getDeviceSession(channel, remoteAddress, buf.readBytes(15).toString(StandardCharsets.UTF_8)); } else { return parseData(channel, remoteAddress, buf, type); } } else { return parseCommandResponse(channel, remoteAddress, buf); } return null; } }
Rename method
src/org/traccar/protocol/AdmProtocolDecoder.java
Rename method
<ide><path>rc/org/traccar/protocol/AdmProtocolDecoder.java <ide> public static final int MSG_PHOTO = 0x0A; <ide> public static final int MSG_ADM5 = 0x01; <ide> <del> private Position parseData(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf, int type) { <add> private Position decodeData(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf, int type) { <ide> DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); <ide> if (deviceSession == null) { <ide> return null; <ide> if (type == MSG_IMEI) { <ide> getDeviceSession(channel, remoteAddress, buf.readBytes(15).toString(StandardCharsets.UTF_8)); <ide> } else { <del> return parseData(channel, remoteAddress, buf, type); <add> return decodeData(channel, remoteAddress, buf, type); <ide> } <ide> } else { <ide> return parseCommandResponse(channel, remoteAddress, buf);
Java
apache-2.0
e3818153c5d76582b0466a2c59cceb0fa0d51fca
0
michel-kraemer/citeproc-java
package de.undercouch.citeproc; import de.undercouch.citeproc.csl.CSLCitation; import de.undercouch.citeproc.csl.CSLCitationItem; import de.undercouch.citeproc.csl.CSLCitationItemBuilder; import de.undercouch.citeproc.csl.CSLItemData; import de.undercouch.citeproc.csl.CSLItemDataBuilder; import de.undercouch.citeproc.csl.internal.GeneratedCitation; import de.undercouch.citeproc.csl.internal.RenderContext; import de.undercouch.citeproc.csl.internal.SSort; import de.undercouch.citeproc.csl.internal.SStyle; import de.undercouch.citeproc.csl.internal.format.AsciiDocFormat; import de.undercouch.citeproc.csl.internal.format.FoFormat; import de.undercouch.citeproc.csl.internal.format.Format; import de.undercouch.citeproc.csl.internal.format.HtmlFormat; import de.undercouch.citeproc.csl.internal.format.TextFormat; import de.undercouch.citeproc.csl.internal.locale.LLocale; import de.undercouch.citeproc.helper.CSLUtils; import de.undercouch.citeproc.output.Bibliography; import de.undercouch.citeproc.output.Citation; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * <p>The citation processor.</p> * * <p>In order to use the processor in your application you first have to * create an {@link ItemDataProvider} that provides citation item data. For * example, the following dummy provider returns always the same data:</p> * * <blockquote><pre> * public class MyItemProvider implements ItemDataProvider { * &#64;Override * public CSLItemData retrieveItem(String id) { * return new CSLItemDataBuilder() * .id(id) * .type(CSLType.ARTICLE_JOURNAL) * .title("A dummy journal article") * .author("John", "Smith") * .issued(2013, 9, 6) * .containerTitle("Dummy journal") * .build(); * } * * &#64;Override * public String[] getIds() { * String ids[] = {"ID-0", "ID-1", "ID-2"}; * return ids; * } * }</pre></blockquote> * * Now you can instantiate the CSL processor. * * <blockquote><pre> * CSL citeproc = new CSL(new MyItemProvider(), "ieee"); * citeproc.setOutputFormat("html");</pre></blockquote> * * <h3>Ad-hoc usage</h3> * * <p>You may also use {@link #makeAdhocBibliography(String, CSLItemData...)} or * {@link #makeAdhocBibliography(String, String, CSLItemData...)} to create * ad-hoc bibliographies from CSL items.</p> * * <blockquote><pre> * CSLItemData item = new CSLItemDataBuilder() * .type(CSLType.WEBPAGE) * .title("citeproc-java: A Citation Style Language (CSL) processor for Java") * .author("Michel", "Kraemer") * .issued(2014, 7, 13) * .URL("http://michel-kraemer.github.io/citeproc-java/") * .accessed(2014, 7, 13) * .build(); * * String bibl = CSL.makeAdhocBibliography("ieee", item).makeString();</pre></blockquote> * * @author Michel Kraemer */ public class CSL { /** * The output format */ private Format outputFormat = new HtmlFormat(); /** * {@code true} if the processor should convert URLs and DOIs in the output * to links. * @see #setConvertLinks(boolean) */ private boolean convertLinks = false; /** * The CSL style used to render citations and bibliographies */ private final SStyle style; /** * The localization data used to render citations and bibliographies */ private final LLocale locale; /** * An object that provides citation item data */ private final ItemDataProvider itemDataProvider; /** * An object that provides abbreviations (may be {@code null}) */ private final AbbreviationProvider abbreviationProvider; /** * Citation items registered through {@link #registerCitationItems(String...)} */ private final Map<String, CSLItemData> registeredItems = new LinkedHashMap<>(); /** * Contains the same items as {@link #registeredItems} but sorted */ private final List<CSLItemData> sortedItems = new ArrayList<>(); /** * A list of generated citations sorted by their index */ private List<GeneratedCitation> generatedCitations = new ArrayList<>(); /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, String style) throws IOException { this(itemDataProvider, new DefaultLocaleProvider(), null, style, "en-US"); } /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param lang an RFC 4646 identifier for the citation locale (e.g. <code>en-US</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, String style, String lang) throws IOException { this(itemDataProvider, new DefaultLocaleProvider(), null, style, lang); } /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param localeProvider an object that provides CSL locales * @param abbreviationProvider an object that provides abbreviations * (may be {@code null}) * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param lang an RFC 4646 identifier for the citation locale (e.g. <code>en-US</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, LocaleProvider localeProvider, AbbreviationProvider abbreviationProvider, String style, String lang) throws IOException { // load style if needed if (!isStyle(style)) { style = loadStyle(style); } this.itemDataProvider = itemDataProvider; this.abbreviationProvider = abbreviationProvider; // TODO parse style and locale directly from URL if possible // TODO instead of loading them into strings first DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Could not create document builder", e); } // load style Document styleDocument; try { styleDocument = builder.parse(new InputSource( new StringReader(style))); } catch (SAXException e) { throw new IOException("Could not parse style", e); } this.style = new SStyle(styleDocument); // load locale String strLocale = localeProvider.retrieveLocale(lang); Document localeDocument; try { localeDocument = builder.parse(new InputSource( new StringReader(strLocale))); } catch (SAXException e) { throw new IOException("Could not parse locale", e); } LLocale locale = new LLocale(localeDocument); for (LLocale l : this.style.getLocales()) { if (l.getLang() == null || (l.getLang().getLanguage().equals(locale.getLang().getLanguage()) && (l.getLang().getCountry().isEmpty() || l.getLang().getCountry().equals(locale.getLang().getCountry())))) { // additional localization data in the style file overrides or // augments the data from the locale file locale = locale.merge(l); } } this.locale = locale; } /** * Get a list of supported output formats * @return the formats */ public static List<String> getSupportedOutputFormats() { return Arrays.asList("asciidoc", "fo", "html", "text"); } private static Set<String> getAvailableFiles(String prefix, String knownName, String extension) throws IOException { Set<String> result = new LinkedHashSet<>(); // first load a file that is known to exist String name = prefix + knownName + "." + extension; URL knownUrl = CSL.class.getResource("/" + name); if (knownUrl != null) { String path = knownUrl.getPath(); // get the jar file containing the file if (path.endsWith(".jar!/" + name)) { String jarPath = path.substring(0, path.length() - name.length() - 2); URI jarUri; try { jarUri = new URI(jarPath); } catch (URISyntaxException e) { // ignore return result; } try (ZipFile zip = new ZipFile(new File(jarUri))) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().endsWith("." + extension) && (prefix.isEmpty() || e.getName().startsWith(prefix))) { result.add(e.getName().substring( prefix.length(), e.getName().length() - 4)); } } } } } return result; } /** * Calculates a list of available citation styles * @return the list * @throws IOException if the citation styles could not be loaded */ public static Set<String> getSupportedStyles() throws IOException { return getAvailableFiles("", "ieee", "csl"); } /** * Checks if a given citation style is supported * @param style the citation style's name * @return true if the style is supported, false otherwise */ public static boolean supportsStyle(String style) { String styleFileName = style; if (!styleFileName.endsWith(".csl")) { styleFileName = styleFileName + ".csl"; } if (!styleFileName.startsWith("/")) { styleFileName = "/" + styleFileName; } URL url = CSL.class.getResource(styleFileName); return (url != null); } /** * Calculates a list of available citation locales * @return the list * @throws IOException if the citation locales could not be loaded */ public static Set<String> getSupportedLocales() throws IOException { return getAvailableFiles("locales-", "en-US", "xml"); } /** * Checks if the given String contains the serialized XML representation * of a style * @param style the string to examine * @return true if the String is XML, false otherwise */ private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); } } return false; } /** * Loads a CSL style from the classpath. For example, if the given name * is <code>ieee</code> this method will load the file <code>/ieee.csl</code> * @param styleName the style's name * @return the serialized XML representation of the style * @throws IOException if the style could not be loaded */ private String loadStyle(String styleName) throws IOException { URL url; if (styleName.startsWith("http://") || styleName.startsWith("https://")) { try { // try to load matching style from classpath return loadStyle(styleName.substring(styleName.lastIndexOf('/') + 1)); } catch (FileNotFoundException e) { // there is no matching style in classpath url = new URL(styleName); } } else { // normalize file name if (!styleName.endsWith(".csl")) { styleName = styleName + ".csl"; } if (!styleName.startsWith("/")) { styleName = "/" + styleName; } // try to find style in classpath url = getClass().getResource(styleName); if (url == null) { throw new FileNotFoundException("Could not find style in " + "classpath: " + styleName); } } // load style String result = CSLUtils.readURLToString(url, "UTF-8"); // handle dependent styles if (isDependent(result)) { String independentParentLink; try { independentParentLink = getIndependentParentLink(result); } catch (ParserConfigurationException | IOException | SAXException e) { throw new IOException("Could not load independent parent style", e); } if (independentParentLink == null) { throw new IOException("Dependent style does not have an " + "independent parent"); } return loadStyle(independentParentLink); } return result; } /** * Test if the given string represents a dependent style * @param style the style * @return true if the string is a dependent style, false otherwise */ private boolean isDependent(String style) { if (!style.trim().startsWith("<")) { return false; } Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\""); Matcher m = p.matcher(style); return m.find(); } /** * Parse a string representing a dependent parent style and * get link to its independent parent style * @param style the dependent style * @return the link to the parent style or <code>null</code> if the link * could not be found * @throws ParserConfigurationException if the XML parser could not be created * @throws IOException if the string could not be read * @throws SAXException if the string could not be parsed */ public String getIndependentParentLink(String style) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource src = new InputSource(new StringReader(style)); Document doc = builder.parse(src); NodeList links = doc.getElementsByTagName("link"); for (int i = 0; i < links.getLength(); ++i) { Node n = links.item(i); Node relAttr = n.getAttributes().getNamedItem("rel"); if (relAttr != null) { if ("independent-parent".equals(relAttr.getTextContent())) { Node hrefAttr = n.getAttributes().getNamedItem("href"); if (hrefAttr != null) { return hrefAttr.getTextContent(); } } } } return null; } /** * Sets the processor's output format * @param format the format (one of {@code "asciidoc"}, {@code "fo"}, * {@code "html"}, and {@code "text"}. */ public void setOutputFormat(String format) { if ("asciidoc".equals(format)) { setOutputFormat(new AsciiDocFormat()); } else if ("fo".equals(format)) { setOutputFormat(new FoFormat()); } else if ("html".equals(format)) { setOutputFormat(new HtmlFormat()); } else if ("text".equals(format)) { setOutputFormat(new TextFormat()); } else { throw new IllegalArgumentException("Unknown output format: `" + format + "'. Supported formats: `asciidoc', `fo', `html', `text'."); } } /** * Sets the processor's output format * @param outputFormat the format */ public void setOutputFormat(Format outputFormat) { this.outputFormat = outputFormat; outputFormat.setConvertLinks(convertLinks); } /** * Specifies if the processor should convert URLs and DOIs in the output * to links. How links are created depends on the output format that has * been set with {@link #setOutputFormat(String)} * @param convert true if URLs and DOIs should be converted to links */ public void setConvertLinks(boolean convert) { convertLinks = convert; outputFormat.setConvertLinks(convert); } /** * Fetches the item data for the given citation items and adds it to * {@link #registeredItems}. Also, sorts the items according to the sorting * specified in the style's bibliography element and stores the result in * {@link #sortedItems}. If the style does not have a bibliography element * or no sorting is specified, the items will just be appended to * {@link #sortedItems}. In addition, the method updates any items already * stored in {@link #sortedItems} and coming after the generated ones. * Updated items will be returned in the given {@code updatedItems} set * (unless it is {@code null}). * @param ids the IDs of the citation items to register * @param updatedItems an empty set that will be filled with the citation * items the method had to update (may be {@code null}) * @param unsorted {@code true} if any sorting specified in the style * should be ignored * @return a list of registered citation item data */ private List<CSLItemData> registerItems(Collection<String> ids, Set<CSLItemData> updatedItems, boolean unsorted) { List<CSLItemData> result = new ArrayList<>(); SSort.SortComparator comparator = null; for (String id : ids) { // check if item has already been registered CSLItemData itemData = registeredItems.get(id); if (itemData != null) { result.add(itemData); continue; } // fetch item data itemData = itemDataProvider.retrieveItem(id); if (itemData == null) { throw new IllegalArgumentException("Missing citation " + "item with ID: " + id); } // register item if (unsorted || style.getBibliography() == null || style.getBibliography().getSort() == null) { // We don't have to sort. Add item to the end of the list. itemData = new CSLItemDataBuilder(itemData) .citationNumber(String.valueOf(registeredItems.size() + 1)) .build(); sortedItems.add(itemData); } else { // We have to sort. Find insert point. if (comparator == null) { comparator = style.getBibliography().getSort() .comparator(style, locale, abbreviationProvider); } int i = Collections.binarySearch(sortedItems, itemData, comparator); if (i < 0) { i = -(i + 1); } else { // binarySearch thinks we found the item in the list but // this is impossible. It's more likely that the comparator // returned 0 because no key was given or it did not yield // sensible results. Just append the item to the list. i = sortedItems.size(); } // determine citation number depending on sort direction int citationNumber; int citationNumberDirection = comparator.getCitationNumberDirection(); if (citationNumberDirection > 0) { citationNumber = i + 1; } else { citationNumber = sortedItems.size() + 1 - i; } // create new item data with citation data and add it to // the list of sorted items itemData = new CSLItemDataBuilder(itemData) .citationNumber(String.valueOf(citationNumber)) .build(); sortedItems.add(i, itemData); // determine if we need to update the following items or // the preceding ones (depending on the sort direction) IntStream idStream; if (citationNumberDirection > 0) { idStream = IntStream.range(i + 1, sortedItems.size()); } else { int e = i; idStream = IntStream.range(0, e).map(n -> e - 1 - n); } // update the other items if necessary idStream.forEach(j -> { CSLItemData item2 = sortedItems.get(j); // determine new citation number int citationNumber2; if (citationNumberDirection > 0) { citationNumber2 = j + 1; } else { citationNumber2 = sortedItems.size() - j; } // create new item data with new citation number item2 = new CSLItemDataBuilder(item2) .citationNumber(String.valueOf(citationNumber2)) .build(); // overwrite existing item data sortedItems.set(j, item2); registeredItems.put(item2.getId(), item2); // store updated item if (updatedItems != null) { updatedItems.add(item2); } }); } // save registered item data registeredItems.put(itemData.getId(), itemData); result.add(itemData); } return result; } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(String... ids) { registerCitationItems(ids, false); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @param unsorted true if items should not be sorted in the bibliography * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(String[] ids, boolean unsorted) { registerCitationItems(Arrays.asList(ids), unsorted); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(Collection<String> ids) { registerCitationItems(ids, false); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @param unsorted true if items should not be sorted in the bibliography * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(Collection<String> ids, boolean unsorted) { registeredItems.clear(); sortedItems.clear(); registerItems(ids, null, unsorted); } /** * Get an unmodifiable collection of all citation items that have been * registered with the processor so far * @return the registered citation items */ public Collection<CSLItemData> getRegisteredItems() { return Collections.unmodifiableCollection(sortedItems); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given * IDs to request the corresponding citation item. Additionally, it saves * the IDs, so {@link #makeBibliography()} will generate a bibliography * that only consists of the retrieved citation items. * @param ids IDs of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public List<Citation> makeCitation(String... ids) { return makeCitation(Arrays.asList(ids)); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given * IDs to request the corresponding citation item. Additionally, it saves * the IDs, so {@link #makeBibliography()} will generate a bibliography * that only consists of the retrieved citation items. * @param ids IDs of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public List<Citation> makeCitation(Collection<String> ids) { CSLCitationItem[] items = new CSLCitationItem[ids.size()]; int i = 0; for (String id : ids) { items[i++] = new CSLCitationItem(id); } return makeCitation(new CSLCitation(items)); } /** * Perform steps to prepare the given citation for rendering. Register * citation items and sort them. Return a prepared citation that can be * passed to {@link #renderCitation(CSLCitation)} * @param citation the citation to render * @param updatedItems an empty set that will be filled with citation * items that had to be updated while rendering the given one (may be * {@code null}) * @return the prepared citation */ private CSLCitation preRenderCitation(CSLCitation citation, Set<CSLItemData> updatedItems) { // get item IDs int len = citation.getCitationItems().length; List<String> itemIds = new ArrayList<>(len); CSLCitationItem[] items = citation.getCitationItems(); for (int i = 0; i < len; i++) { CSLCitationItem item = items[i]; itemIds.add(item.getId()); } // register items List<CSLItemData> registeredItems = registerItems(itemIds, updatedItems, false); // prepare items CSLCitationItem[] preparedItems = new CSLCitationItem[len]; for (int i = 0; i < len; i++) { CSLCitationItem item = items[i]; CSLItemData itemData = registeredItems.get(i); // overwrite locator if (item.getLocator() != null) { itemData = new CSLItemDataBuilder(itemData) .locator(item.getLocator()) .build(); } preparedItems[i] = new CSLCitationItemBuilder(item) .itemData(itemData) .build(); } // sort array of items boolean unsorted = false; if (citation.getProperties() != null && citation.getProperties().getUnsorted() != null) { unsorted = citation.getProperties().getUnsorted(); } if (!unsorted && style.getCitation().getSort() != null) { Comparator<CSLItemData> itemComparator = style.getCitation().getSort().comparator(style, locale, abbreviationProvider); Arrays.sort(preparedItems, (a, b) -> itemComparator.compare( a.getItemData(), b.getItemData())); } return new CSLCitation(preparedItems, citation.getCitationID(), citation.getProperties()); } /** * Render the given prepared citation * @param preparedCitation the citation to render. The citation must have * been prepared by {@link #preRenderCitation(CSLCitation, Set)} * @return the rendered string */ private String renderCitation(CSLCitation preparedCitation) { // render items RenderContext ctx = new RenderContext(style, locale, null, abbreviationProvider, preparedCitation, Collections.unmodifiableList(generatedCitations)); style.getCitation().render(ctx); return outputFormat.formatCitation(ctx); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each item in the * given set to request the corresponding citation item data. Additionally, * it saves the requested citation IDs, so {@link #makeBibliography()} will * generate a bibliography that only consists of the retrieved items. * @param citation a set of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if the given set of citation items * refers to citation item data that does not exist */ public List<Citation> makeCitation(CSLCitation citation) { Set<CSLItemData> updatedItems = new LinkedHashSet<>(); CSLCitation preparedCitation = preRenderCitation(citation, updatedItems); String text = renderCitation(preparedCitation); // re-render updated citations List<Citation> result = new ArrayList<>(); if (!updatedItems.isEmpty()) { List<GeneratedCitation> oldGeneratedCitations = generatedCitations; generatedCitations = new ArrayList<>(oldGeneratedCitations.size()); for (int i = 0; i < oldGeneratedCitations.size(); i++) { GeneratedCitation gc = oldGeneratedCitations.get(i); boolean needsUpdate = false; for (CSLItemData updatedItemData : updatedItems) { for (CSLCitationItem item : gc.getOriginal().getCitationItems()) { if (item.getId().equals(updatedItemData.getId())) { needsUpdate = true; break; } } } if (!needsUpdate) { generatedCitations.add(gc); continue; } // prepare citation again (!) CSLCitation upc = preRenderCitation(gc.getOriginal(), null); // render it again String ut = renderCitation(upc); if (!ut.equals(gc.getGenerated().getText())) { // render result was different Citation uc = new Citation(i, ut); generatedCitations.add(new GeneratedCitation( gc.getOriginal(), upc, uc)); result.add(uc); } } } // generate citation Citation generatedCitation = new Citation(generatedCitations.size(), text); generatedCitations.add(new GeneratedCitation(citation, preparedCitation, generatedCitation)); result.add(generatedCitation); return result; } /** * Generates a bibliography for the registered citations * @return the bibliography */ public Bibliography makeBibliography() { return makeBibliography(null); } /** * Generates a bibliography for the registered citations. Depending * on the selection mode selects, includes, or excludes bibliography * items whose fields and field values match the fields and field values * from the given example item data objects. * @param mode the selection mode * @param selection the example item data objects that contain * the fields and field values to match * @return the bibliography */ public Bibliography makeBibliography(SelectionMode mode, CSLItemData... selection) { return makeBibliography(mode, selection, null); } /** * <p>Generates a bibliography for the registered citations. Depending * on the selection mode selects, includes, or excludes bibliography * items whose fields and field values match the fields and field values * from the given example item data objects.</p> * <p>Note: This method will be deprecated in the next release.</p> * @param mode the selection mode * @param selection the example item data objects that contain * the fields and field values to match * @param quash regardless of the item data in {@code selection} * skip items if all fields/values from this list match * @return the bibliography */ public Bibliography makeBibliography(SelectionMode mode, CSLItemData[] selection, CSLItemData[] quash) { return makeBibliography(item -> { boolean include = true; if (selection != null) { switch (mode) { case INCLUDE: include = false; for (CSLItemData s : selection) { if (itemDataEqualsAny(item, s)) { include = true; break; } } break; case EXCLUDE: for (CSLItemData s : selection) { if (itemDataEqualsAny(item, s)) { include = false; break; } } break; case SELECT: for (CSLItemData s : selection) { if (!itemDataEqualsAny(item, s)) { include = false; break; } } break; } } if (include && quash != null) { boolean match = true; for (CSLItemData s : quash) { if (!itemDataEqualsAny(item, s)) { match = false; break; } } if (match) { include = false; } } return include; }); } /** * Generates a bibliography for registered citations * @param filter a function to apply to each registered citation item to * determine if it should be included in the bibliography or not (may * be {@code null} if all items should be included) * @return the bibliography */ public Bibliography makeBibliography(Predicate<CSLItemData> filter) { List<CSLItemData> filteredItems; if (filter == null) { filteredItems = sortedItems; } else { filteredItems = new ArrayList<>(); for (CSLItemData item : sortedItems) { if (filter.test(item)) { filteredItems.add(item); } } } List<String> entries = new ArrayList<>(); for (int i = 0; i < filteredItems.size(); i++) { CSLItemData item = filteredItems.get(i); RenderContext ctx = new RenderContext(style, locale, item, abbreviationProvider); style.getBibliography().render(ctx); if (!ctx.getResult().isEmpty()) { entries.add(outputFormat.formatBibliographyEntry(ctx, i)); } } return outputFormat.makeBibliography(entries.toArray(new String[0]), style.getBibliography()); } /** * Resets the processor's state */ public void reset() { outputFormat = new HtmlFormat(); convertLinks = false; registeredItems.clear(); sortedItems.clear(); generatedCitations.clear(); } /** * Creates an ad hoc bibliography from the given citation items using the * <code>"html"</code> output format. * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param items the citation items to add to the bibliography * @return the bibliography * @throws IOException if the underlying JavaScript files or the CSL style * could not be loaded * @see #makeAdhocBibliography(String, String, CSLItemData...) */ public static Bibliography makeAdhocBibliography(String style, CSLItemData... items) throws IOException { return makeAdhocBibliography(style, "html", items); } /** * Creates an ad hoc bibliography from the given citation items. * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param outputFormat the processor's output format (one of * <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>, * <code>"fo"</code>, or <code>"rtf"</code>) * @param items the citation items to add to the bibliography * @return the bibliography * @throws IOException if the CSL style could not be loaded */ public static Bibliography makeAdhocBibliography(String style, String outputFormat, CSLItemData... items) throws IOException { ItemDataProvider provider = new ListItemDataProvider(items); CSL csl = new CSL(provider, style); csl.setOutputFormat(outputFormat); String[] ids = new String[items.length]; for (int i = 0; i < items.length; ++i) { ids[i] = items[i].getId(); } csl.registerCitationItems(ids); return csl.makeBibliography(); } /** * Test if any of the attributes of {@code b} match the ones of {@code a}. * Note: This method will be deprecated in the next release * @param a the first object * @param b the object to match against * @return {@code true} if the match succeeds */ private static boolean itemDataEqualsAny(CSLItemData a, CSLItemData b) { if (a == b) { return true; } if (b == null) { return false; } if (b.getId() != null && Objects.equals(a.getId(), b.getId())) { return true; } if (b.getType() != null && Objects.equals(a.getType(), b.getType())) { return true; } if (b.getCategories() != null && Arrays.equals(a.getCategories(), b.getCategories())) { return true; } if (b.getLanguage() != null && Objects.equals(a.getLanguage(), b.getLanguage())) { return true; } if (b.getJournalAbbreviation() != null && Objects.equals(a.getJournalAbbreviation(), b.getJournalAbbreviation())) { return true; } if (b.getShortTitle() != null && Objects.equals(a.getShortTitle(), b.getShortTitle())) { return true; } if (b.getAuthor() != null && Arrays.equals(a.getAuthor(), b.getAuthor())) { return true; } if (b.getCollectionEditor() != null && Arrays.equals(a.getCollectionEditor(), b.getCollectionEditor())) { return true; } if (b.getComposer() != null && Arrays.equals(a.getComposer(), b.getComposer())) { return true; } if (b.getContainerAuthor() != null && Arrays.equals(a.getContainerAuthor(), b.getContainerAuthor())) { return true; } if (b.getDirector() != null && Arrays.equals(a.getDirector(), b.getDirector())) { return true; } if (b.getEditor() != null && Arrays.equals(a.getEditor(), b.getEditor())) { return true; } if (b.getEditorialDirector() != null && Arrays.equals(a.getEditorialDirector(), b.getEditorialDirector())) { return true; } if (b.getInterviewer() != null && Arrays.equals(a.getInterviewer(), b.getInterviewer())) { return true; } if (b.getIllustrator() != null && Arrays.equals(a.getIllustrator(), b.getIllustrator())) { return true; } if (b.getOriginalAuthor() != null && Arrays.equals(a.getOriginalAuthor(), b.getOriginalAuthor())) { return true; } if (b.getRecipient() != null && Arrays.equals(a.getRecipient(), b.getRecipient())) { return true; } if (b.getReviewedAuthor() != null && Arrays.equals(a.getReviewedAuthor(), b.getReviewedAuthor())) { return true; } if (b.getTranslator() != null && Arrays.equals(a.getTranslator(), b.getTranslator())) { return true; } if (b.getAccessed() != null && Objects.equals(a.getAccessed(), b.getAccessed())) { return true; } if (b.getContainer() != null && Objects.equals(a.getContainer(), b.getContainer())) { return true; } if (b.getEventDate() != null && Objects.equals(a.getEventDate(), b.getEventDate())) { return true; } if (b.getIssued() != null && Objects.equals(a.getIssued(), b.getIssued())) { return true; } if (b.getOriginalDate() != null && Objects.equals(a.getOriginalDate(), b.getOriginalDate())) { return true; } if (b.getSubmitted() != null && Objects.equals(a.getSubmitted(), b.getSubmitted())) { return true; } if (b.getAbstrct() != null && Objects.equals(a.getAbstrct(), b.getAbstrct())) { return true; } if (b.getAnnote() != null && Objects.equals(a.getAnnote(), b.getAnnote())) { return true; } if (b.getArchive() != null && Objects.equals(a.getArchive(), b.getArchive())) { return true; } if (b.getArchiveLocation() != null && Objects.equals(a.getArchiveLocation(), b.getArchiveLocation())) { return true; } if (b.getArchivePlace() != null && Objects.equals(a.getArchivePlace(), b.getArchivePlace())) { return true; } if (b.getAuthority() != null && Objects.equals(a.getAuthority(), b.getAuthority())) { return true; } if (b.getCallNumber() != null && Objects.equals(a.getCallNumber(), b.getCallNumber())) { return true; } if (b.getChapterNumber() != null && Objects.equals(a.getChapterNumber(), b.getChapterNumber())) { return true; } if (b.getCitationNumber() != null && Objects.equals(a.getCitationNumber(), b.getCitationNumber())) { return true; } if (b.getCitationLabel() != null && Objects.equals(a.getCitationLabel(), b.getCitationLabel())) { return true; } if (b.getCollectionNumber() != null && Objects.equals(a.getCollectionNumber(), b.getCollectionNumber())) { return true; } if (b.getCollectionTitle() != null && Objects.equals(a.getCollectionTitle(), b.getCollectionTitle())) { return true; } if (b.getContainerTitle() != null && Objects.equals(a.getContainerTitle(), b.getContainerTitle())) { return true; } if (b.getContainerTitleShort() != null && Objects.equals(a.getContainerTitleShort(), b.getContainerTitleShort())) { return true; } if (b.getDimensions() != null && Objects.equals(a.getDimensions(), b.getDimensions())) { return true; } if (b.getDOI() != null && Objects.equals(a.getDOI(), b.getDOI())) { return true; } if (b.getEdition() != null && Objects.equals(a.getEdition(), b.getEdition())) { return true; } if (b.getEvent() != null && Objects.equals(a.getEvent(), b.getEvent())) { return true; } if (b.getEventPlace() != null && Objects.equals(a.getEventPlace(), b.getEventPlace())) { return true; } if (b.getFirstReferenceNoteNumber() != null && Objects.equals(a.getFirstReferenceNoteNumber(), b.getFirstReferenceNoteNumber())) { return true; } if (b.getGenre() != null && Objects.equals(a.getGenre(), b.getGenre())) { return true; } if (b.getISBN() != null && Objects.equals(a.getISBN(), b.getISBN())) { return true; } if (b.getISSN() != null && Objects.equals(a.getISSN(), b.getISSN())) { return true; } if (b.getIssue() != null && Objects.equals(a.getIssue(), b.getIssue())) { return true; } if (b.getJurisdiction() != null && Objects.equals(a.getJurisdiction(), b.getJurisdiction())) { return true; } if (b.getKeyword() != null && Objects.equals(a.getKeyword(), b.getKeyword())) { return true; } if (b.getLocator() != null && Objects.equals(a.getLocator(), b.getLocator())) { return true; } if (b.getMedium() != null && Objects.equals(a.getMedium(), b.getMedium())) { return true; } if (b.getNote() != null && Objects.equals(a.getNote(), b.getNote())) { return true; } if (b.getNumber() != null && Objects.equals(a.getNumber(), b.getNumber())) { return true; } if (b.getNumberOfPages() != null && Objects.equals(a.getNumberOfPages(), b.getNumberOfPages())) { return true; } if (b.getNumberOfVolumes() != null && Objects.equals(a.getNumberOfVolumes(), b.getNumberOfVolumes())) { return true; } if (b.getOriginalPublisher() != null && Objects.equals(a.getOriginalPublisher(), b.getOriginalPublisher())) { return true; } if (b.getOriginalPublisherPlace() != null && Objects.equals(a.getOriginalPublisherPlace(), b.getOriginalPublisherPlace())) { return true; } if (b.getOriginalTitle() != null && Objects.equals(a.getOriginalTitle(), b.getOriginalTitle())) { return true; } if (b.getPage() != null && Objects.equals(a.getPage(), b.getPage())) { return true; } if (b.getPageFirst() != null && Objects.equals(a.getPageFirst(), b.getPageFirst())) { return true; } if (b.getPMCID() != null && Objects.equals(a.getPMCID(), b.getPMCID())) { return true; } if (b.getPMID() != null && Objects.equals(a.getPMID(), b.getPMID())) { return true; } if (b.getPublisher() != null && Objects.equals(a.getPublisher(), b.getPublisher())) { return true; } if (b.getPublisherPlace() != null && Objects.equals(a.getPublisherPlace(), b.getPublisherPlace())) { return true; } if (b.getReferences() != null && Objects.equals(a.getReferences(), b.getReferences())) { return true; } if (b.getReviewedTitle() != null && Objects.equals(a.getReviewedTitle(), b.getReviewedTitle())) { return true; } if (b.getScale() != null && Objects.equals(a.getScale(), b.getScale())) { return true; } if (b.getSection() != null && Objects.equals(a.getSection(), b.getSection())) { return true; } if (b.getSource() != null && Objects.equals(a.getSource(), b.getSource())) { return true; } if (b.getStatus() != null && Objects.equals(a.getStatus(), b.getStatus())) { return true; } if (b.getTitle() != null && Objects.equals(a.getTitle(), b.getTitle())) { return true; } if (b.getTitleShort() != null && Objects.equals(a.getTitleShort(), b.getTitleShort())) { return true; } if (b.getURL() != null && Objects.equals(a.getURL(), b.getURL())) { return true; } if (b.getVersion() != null && Objects.equals(a.getVersion(), b.getVersion())) { return true; } if (b.getVolume() != null && Objects.equals(a.getVolume(), b.getVolume())) { return true; } return b.getYearSuffix() != null && Objects.equals(a.getYearSuffix(), b.getYearSuffix()); } }
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
package de.undercouch.citeproc; import de.undercouch.citeproc.csl.CSLCitation; import de.undercouch.citeproc.csl.CSLCitationItem; import de.undercouch.citeproc.csl.CSLCitationItemBuilder; import de.undercouch.citeproc.csl.CSLItemData; import de.undercouch.citeproc.csl.CSLItemDataBuilder; import de.undercouch.citeproc.csl.internal.GeneratedCitation; import de.undercouch.citeproc.csl.internal.RenderContext; import de.undercouch.citeproc.csl.internal.SSort; import de.undercouch.citeproc.csl.internal.SStyle; import de.undercouch.citeproc.csl.internal.format.AsciiDocFormat; import de.undercouch.citeproc.csl.internal.format.FoFormat; import de.undercouch.citeproc.csl.internal.format.Format; import de.undercouch.citeproc.csl.internal.format.HtmlFormat; import de.undercouch.citeproc.csl.internal.format.TextFormat; import de.undercouch.citeproc.csl.internal.locale.LLocale; import de.undercouch.citeproc.helper.CSLUtils; import de.undercouch.citeproc.output.Bibliography; import de.undercouch.citeproc.output.Citation; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.IntStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * <p>The citation processor.</p> * * <p>In order to use the processor in your application you first have to * create an {@link ItemDataProvider} that provides citation item data. For * example, the following dummy provider returns always the same data:</p> * * <blockquote><pre> * public class MyItemProvider implements ItemDataProvider { * &#64;Override * public CSLItemData retrieveItem(String id) { * return new CSLItemDataBuilder() * .id(id) * .type(CSLType.ARTICLE_JOURNAL) * .title("A dummy journal article") * .author("John", "Smith") * .issued(2013, 9, 6) * .containerTitle("Dummy journal") * .build(); * } * * &#64;Override * public String[] getIds() { * String ids[] = {"ID-0", "ID-1", "ID-2"}; * return ids; * } * }</pre></blockquote> * * Now you can instantiate the CSL processor. * * <blockquote><pre> * CSL citeproc = new CSL(new MyItemProvider(), "ieee"); * citeproc.setOutputFormat("html");</pre></blockquote> * * <h3>Ad-hoc usage</h3> * * <p>You may also use {@link #makeAdhocBibliography(String, CSLItemData...)} or * {@link #makeAdhocBibliography(String, String, CSLItemData...)} to create * ad-hoc bibliographies from CSL items.</p> * * <blockquote><pre> * CSLItemData item = new CSLItemDataBuilder() * .type(CSLType.WEBPAGE) * .title("citeproc-java: A Citation Style Language (CSL) processor for Java") * .author("Michel", "Kraemer") * .issued(2014, 7, 13) * .URL("http://michel-kraemer.github.io/citeproc-java/") * .accessed(2014, 7, 13) * .build(); * * String bibl = CSL.makeAdhocBibliography("ieee", item).makeString();</pre></blockquote> * * @author Michel Kraemer */ public class CSL { /** * The output format */ private Format outputFormat = new HtmlFormat(); /** * {@code true} if the processor should convert URLs and DOIs in the output * to links. * @see #setConvertLinks(boolean) */ private boolean convertLinks = false; /** * The CSL style used to render citations and bibliographies */ private final SStyle style; /** * The localization data used to render citations and bibliographies */ private final LLocale locale; /** * An object that provides citation item data */ private final ItemDataProvider itemDataProvider; /** * An object that provides abbreviations (may be {@link null}) */ private final AbbreviationProvider abbreviationProvider; /** * Citation items registered through {@link #registerCitationItems(String...)} */ private final Map<String, CSLItemData> registeredItems = new LinkedHashMap<>(); /** * Contains the same items as {@link #registeredItems} but sorted */ private final List<CSLItemData> sortedItems = new ArrayList<>(); /** * A list of generated citations sorted by their index */ private List<GeneratedCitation> generatedCitations = new ArrayList<>(); /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, String style) throws IOException { this(itemDataProvider, new DefaultLocaleProvider(), null, style, "en-US"); } /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param lang an RFC 4646 identifier for the citation locale (e.g. <code>en-US</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, String style, String lang) throws IOException { this(itemDataProvider, new DefaultLocaleProvider(), null, style, lang); } /** * Constructs a new citation processor * @param itemDataProvider an object that provides citation item data * @param localeProvider an object that provides CSL locales * @param abbreviationProvider an object that provides abbreviations * (may be {@link null}) * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param lang an RFC 4646 identifier for the citation locale (e.g. <code>en-US</code>) * @throws IOException if the CSL style could not be loaded */ public CSL(ItemDataProvider itemDataProvider, LocaleProvider localeProvider, AbbreviationProvider abbreviationProvider, String style, String lang) throws IOException { // load style if needed if (!isStyle(style)) { style = loadStyle(style); } this.itemDataProvider = itemDataProvider; this.abbreviationProvider = abbreviationProvider; // TODO parse style and locale directly from URL if possible // TODO instead of loading them into strings first DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Could not create document builder", e); } // load style Document styleDocument; try { styleDocument = builder.parse(new InputSource( new StringReader(style))); } catch (SAXException e) { throw new IOException("Could not parse style", e); } this.style = new SStyle(styleDocument); // load locale String strLocale = localeProvider.retrieveLocale(lang); Document localeDocument; try { localeDocument = builder.parse(new InputSource( new StringReader(strLocale))); } catch (SAXException e) { throw new IOException("Could not parse locale", e); } LLocale locale = new LLocale(localeDocument); for (LLocale l : this.style.getLocales()) { if (l.getLang() == null || (l.getLang().getLanguage().equals(locale.getLang().getLanguage()) && (l.getLang().getCountry().isEmpty() || l.getLang().getCountry().equals(locale.getLang().getCountry())))) { // additional localization data in the style file overrides or // augments the data from the locale file locale = locale.merge(l); } } this.locale = locale; } /** * Get a list of supported output formats * @return the formats */ public static List<String> getSupportedOutputFormats() { return Arrays.asList("asciidoc", "fo", "html", "text"); } private static Set<String> getAvailableFiles(String prefix, String knownName, String extension) throws IOException { Set<String> result = new LinkedHashSet<>(); // first load a file that is known to exist String name = prefix + knownName + "." + extension; URL knownUrl = CSL.class.getResource("/" + name); if (knownUrl != null) { String path = knownUrl.getPath(); // get the jar file containing the file if (path.endsWith(".jar!/" + name)) { String jarPath = path.substring(0, path.length() - name.length() - 2); URI jarUri; try { jarUri = new URI(jarPath); } catch (URISyntaxException e) { // ignore return result; } try (ZipFile zip = new ZipFile(new File(jarUri))) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); if (e.getName().endsWith("." + extension) && (prefix.isEmpty() || e.getName().startsWith(prefix))) { result.add(e.getName().substring( prefix.length(), e.getName().length() - 4)); } } } } } return result; } /** * Calculates a list of available citation styles * @return the list * @throws IOException if the citation styles could not be loaded */ public static Set<String> getSupportedStyles() throws IOException { return getAvailableFiles("", "ieee", "csl"); } /** * Checks if a given citation style is supported * @param style the citation style's name * @return true if the style is supported, false otherwise */ public static boolean supportsStyle(String style) { String styleFileName = style; if (!styleFileName.endsWith(".csl")) { styleFileName = styleFileName + ".csl"; } if (!styleFileName.startsWith("/")) { styleFileName = "/" + styleFileName; } URL url = CSL.class.getResource(styleFileName); return (url != null); } /** * Calculates a list of available citation locales * @return the list * @throws IOException if the citation locales could not be loaded */ public static Set<String> getSupportedLocales() throws IOException { return getAvailableFiles("locales-", "en-US", "xml"); } /** * Checks if the given String contains the serialized XML representation * of a style * @param style the string to examine * @return true if the String is XML, false otherwise */ private boolean isStyle(String style) { for (int i = 0; i < style.length(); ++i) { char c = style.charAt(i); if (!Character.isWhitespace(c)) { return (c == '<'); } } return false; } /** * Loads a CSL style from the classpath. For example, if the given name * is <code>ieee</code> this method will load the file <code>/ieee.csl</code> * @param styleName the style's name * @return the serialized XML representation of the style * @throws IOException if the style could not be loaded */ private String loadStyle(String styleName) throws IOException { URL url; if (styleName.startsWith("http://") || styleName.startsWith("https://")) { try { // try to load matching style from classpath return loadStyle(styleName.substring(styleName.lastIndexOf('/') + 1)); } catch (FileNotFoundException e) { // there is no matching style in classpath url = new URL(styleName); } } else { // normalize file name if (!styleName.endsWith(".csl")) { styleName = styleName + ".csl"; } if (!styleName.startsWith("/")) { styleName = "/" + styleName; } // try to find style in classpath url = getClass().getResource(styleName); if (url == null) { throw new FileNotFoundException("Could not find style in " + "classpath: " + styleName); } } // load style String result = CSLUtils.readURLToString(url, "UTF-8"); // handle dependent styles if (isDependent(result)) { String independentParentLink; try { independentParentLink = getIndependentParentLink(result); } catch (ParserConfigurationException | IOException | SAXException e) { throw new IOException("Could not load independent parent style", e); } if (independentParentLink == null) { throw new IOException("Dependent style does not have an " + "independent parent"); } return loadStyle(independentParentLink); } return result; } /** * Test if the given string represents a dependent style * @param style the style * @return true if the string is a dependent style, false otherwise */ private boolean isDependent(String style) { if (!style.trim().startsWith("<")) { return false; } Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\""); Matcher m = p.matcher(style); return m.find(); } /** * Parse a string representing a dependent parent style and * get link to its independent parent style * @param style the dependent style * @return the link to the parent style or <code>null</code> if the link * could not be found * @throws ParserConfigurationException if the XML parser could not be created * @throws IOException if the string could not be read * @throws SAXException if the string could not be parsed */ public String getIndependentParentLink(String style) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource src = new InputSource(new StringReader(style)); Document doc = builder.parse(src); NodeList links = doc.getElementsByTagName("link"); for (int i = 0; i < links.getLength(); ++i) { Node n = links.item(i); Node relAttr = n.getAttributes().getNamedItem("rel"); if (relAttr != null) { if ("independent-parent".equals(relAttr.getTextContent())) { Node hrefAttr = n.getAttributes().getNamedItem("href"); if (hrefAttr != null) { return hrefAttr.getTextContent(); } } } } return null; } /** * Sets the processor's output format * @param format the format (one of {@code "asciidoc"}, {@code "fo"}, * {@code "html"}, and {@code "text"}. */ public void setOutputFormat(String format) { if ("asciidoc".equals(format)) { setOutputFormat(new AsciiDocFormat()); } else if ("fo".equals(format)) { setOutputFormat(new FoFormat()); } else if ("html".equals(format)) { setOutputFormat(new HtmlFormat()); } else if ("text".equals(format)) { setOutputFormat(new TextFormat()); } else { throw new IllegalArgumentException("Unknown output format: `" + format + "'. Supported formats: `asciidoc', `fo', `html', `text'."); } } /** * Sets the processor's output format * @param outputFormat the format */ public void setOutputFormat(Format outputFormat) { this.outputFormat = outputFormat; outputFormat.setConvertLinks(convertLinks); } /** * Specifies if the processor should convert URLs and DOIs in the output * to links. How links are created depends on the output format that has * been set with {@link #setOutputFormat(String)} * @param convert true if URLs and DOIs should be converted to links */ public void setConvertLinks(boolean convert) { convertLinks = convert; outputFormat.setConvertLinks(convert); } /** * Fetches the item data for the given citation items and adds it to * {@link #registeredItems}. Also, sorts the items according to the sorting * specified in the style's bibliography element and stores the result in * {@link #sortedItems}. If the style does not have a bibliography element * or no sorting is specified, the items will just be appended to * {@link #sortedItems}. In addition, the method updates any items already * stored in {@link #sortedItems} and coming after the generated ones. * Updated items will be returned in the given {@code updatedItems} set * (unless it is {@code null}). * @param ids the IDs of the citation items to register * @param updatedItems an empty set that will be filled with the citation * items the method had to update (may be {@code null}) * @param unsorted {@code true} if any sorting specified in the style * should be ignored * @return a list of registered citation item data */ private List<CSLItemData> registerItems(Collection<String> ids, Set<CSLItemData> updatedItems, boolean unsorted) { List<CSLItemData> result = new ArrayList<>(); SSort.SortComparator comparator = null; for (String id : ids) { // check if item has already been registered CSLItemData itemData = registeredItems.get(id); if (itemData != null) { result.add(itemData); continue; } // fetch item data itemData = itemDataProvider.retrieveItem(id); if (itemData == null) { throw new IllegalArgumentException("Missing citation " + "item with ID: " + id); } // register item if (unsorted || style.getBibliography() == null || style.getBibliography().getSort() == null) { // We don't have to sort. Add item to the end of the list. itemData = new CSLItemDataBuilder(itemData) .citationNumber(String.valueOf(registeredItems.size() + 1)) .build(); sortedItems.add(itemData); } else { // We have to sort. Find insert point. if (comparator == null) { comparator = style.getBibliography().getSort() .comparator(style, locale, abbreviationProvider); } int i = Collections.binarySearch(sortedItems, itemData, comparator); if (i < 0) { i = -(i + 1); } else { // binarySearch thinks we found the item in the list but // this is impossible. It's more likely that the comparator // returned 0 because no key was given or it did not yield // sensible results. Just append the item to the list. i = sortedItems.size(); } // determine citation number depending on sort direction int citationNumber; int citationNumberDirection = comparator.getCitationNumberDirection(); if (citationNumberDirection > 0) { citationNumber = i + 1; } else { citationNumber = sortedItems.size() + 1 - i; } // create new item data with citation data and add it to // the list of sorted items itemData = new CSLItemDataBuilder(itemData) .citationNumber(String.valueOf(citationNumber)) .build(); sortedItems.add(i, itemData); // determine if we need to update the following items or // the preceding ones (depending on the sort direction) IntStream idStream; if (citationNumberDirection > 0) { idStream = IntStream.range(i + 1, sortedItems.size()); } else { int e = i; idStream = IntStream.range(0, e).map(n -> e - 1 - n); } // update the other items if necessary idStream.forEach(j -> { CSLItemData item2 = sortedItems.get(j); // determine new citation number int citationNumber2; if (citationNumberDirection > 0) { citationNumber2 = j + 1; } else { citationNumber2 = sortedItems.size() - j; } // create new item data with new citation number item2 = new CSLItemDataBuilder(item2) .citationNumber(String.valueOf(citationNumber2)) .build(); // overwrite existing item data sortedItems.set(j, item2); registeredItems.put(item2.getId(), item2); // store updated item if (updatedItems != null) { updatedItems.add(item2); } }); } // save registered item data registeredItems.put(itemData.getId(), itemData); result.add(itemData); } return result; } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(String... ids) { registerCitationItems(ids, false); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @param unsorted true if items should not be sorted in the bibliography * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(String[] ids, boolean unsorted) { registerCitationItems(Arrays.asList(ids), unsorted); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(Collection<String> ids) { registerCitationItems(ids, false); } /** * Introduces the given citation IDs to the processor. The processor will * call {@link ItemDataProvider#retrieveItem(String)} for each ID to get * the respective citation item. The retrieved items will be added to the * bibliography, so you don't have to call {@link #makeCitation(String...)} * for each of them anymore. * @param ids the IDs to register * @param unsorted true if items should not be sorted in the bibliography * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public void registerCitationItems(Collection<String> ids, boolean unsorted) { registeredItems.clear(); sortedItems.clear(); registerItems(ids, null, unsorted); } /** * Get an unmodifiable collection of all citation items that have been * registered with the processor so far * @return the registered citation items */ public Collection<CSLItemData> getRegisteredItems() { return Collections.unmodifiableCollection(sortedItems); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given * IDs to request the corresponding citation item. Additionally, it saves * the IDs, so {@link #makeBibliography()} will generate a bibliography * that only consists of the retrieved citation items. * @param ids IDs of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public List<Citation> makeCitation(String... ids) { return makeCitation(Arrays.asList(ids)); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given * IDs to request the corresponding citation item. Additionally, it saves * the IDs, so {@link #makeBibliography()} will generate a bibliography * that only consists of the retrieved citation items. * @param ids IDs of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if one of the given IDs refers to * citation item data that does not exist */ public List<Citation> makeCitation(Collection<String> ids) { CSLCitationItem[] items = new CSLCitationItem[ids.size()]; int i = 0; for (String id : ids) { items[i++] = new CSLCitationItem(id); } return makeCitation(new CSLCitation(items)); } /** * Perform steps to prepare the given citation for rendering. Register * citation items and sort them. Return a prepared citation that can be * passed to {@link #renderCitation(CSLCitation)} * @param citation the citation to render * @param updatedItems an empty set that will be filled with citation * items that had to be updated while rendering the given one (may be * {@code null}) * @return the prepared citation */ private CSLCitation preRenderCitation(CSLCitation citation, Set<CSLItemData> updatedItems) { // get item IDs int len = citation.getCitationItems().length; List<String> itemIds = new ArrayList<>(len); CSLCitationItem[] items = citation.getCitationItems(); for (int i = 0; i < len; i++) { CSLCitationItem item = items[i]; itemIds.add(item.getId()); } // register items List<CSLItemData> registeredItems = registerItems(itemIds, updatedItems, false); // prepare items CSLCitationItem[] preparedItems = new CSLCitationItem[len]; for (int i = 0; i < len; i++) { CSLCitationItem item = items[i]; CSLItemData itemData = registeredItems.get(i); // overwrite locator if (item.getLocator() != null) { itemData = new CSLItemDataBuilder(itemData) .locator(item.getLocator()) .build(); } preparedItems[i] = new CSLCitationItemBuilder(item) .itemData(itemData) .build(); } // sort array of items boolean unsorted = false; if (citation.getProperties() != null && citation.getProperties().getUnsorted() != null) { unsorted = citation.getProperties().getUnsorted(); } if (!unsorted && style.getCitation().getSort() != null) { Comparator<CSLItemData> itemComparator = style.getCitation().getSort().comparator(style, locale, abbreviationProvider); Arrays.sort(preparedItems, (a, b) -> itemComparator.compare( a.getItemData(), b.getItemData())); } return new CSLCitation(preparedItems, citation.getCitationID(), citation.getProperties()); } /** * Render the given prepared citation * @param preparedCitation the citation to render. The citation must have * been prepared by {@link #preRenderCitation(CSLCitation, Set)} * @return the rendered string */ private String renderCitation(CSLCitation preparedCitation) { // render items RenderContext ctx = new RenderContext(style, locale, null, abbreviationProvider, preparedCitation, Collections.unmodifiableList(generatedCitations)); style.getCitation().render(ctx); return outputFormat.formatCitation(ctx); } /** * Generates citation strings that can be inserted into the text. The * method calls {@link ItemDataProvider#retrieveItem(String)} for each item in the * given set to request the corresponding citation item data. Additionally, * it saves the requested citation IDs, so {@link #makeBibliography()} will * generate a bibliography that only consists of the retrieved items. * @param citation a set of citation items for which strings should be generated * @return citations strings that can be inserted into the text * @throws IllegalArgumentException if the given set of citation items * refers to citation item data that does not exist */ public List<Citation> makeCitation(CSLCitation citation) { Set<CSLItemData> updatedItems = new LinkedHashSet<>(); CSLCitation preparedCitation = preRenderCitation(citation, updatedItems); String text = renderCitation(preparedCitation); // re-render updated citations List<Citation> result = new ArrayList<>(); if (!updatedItems.isEmpty()) { List<GeneratedCitation> oldGeneratedCitations = generatedCitations; generatedCitations = new ArrayList<>(oldGeneratedCitations.size()); for (int i = 0; i < oldGeneratedCitations.size(); i++) { GeneratedCitation gc = oldGeneratedCitations.get(i); boolean needsUpdate = false; for (CSLItemData updatedItemData : updatedItems) { for (CSLCitationItem item : gc.getOriginal().getCitationItems()) { if (item.getId().equals(updatedItemData.getId())) { needsUpdate = true; break; } } } if (!needsUpdate) { generatedCitations.add(gc); continue; } // prepare citation again (!) CSLCitation upc = preRenderCitation(gc.getOriginal(), null); // render it again String ut = renderCitation(upc); if (!ut.equals(gc.getGenerated().getText())) { // render result was different Citation uc = new Citation(i, ut); generatedCitations.add(new GeneratedCitation( gc.getOriginal(), upc, uc)); result.add(uc); } } } // generate citation Citation generatedCitation = new Citation(generatedCitations.size(), text); generatedCitations.add(new GeneratedCitation(citation, preparedCitation, generatedCitation)); result.add(generatedCitation); return result; } /** * Generates a bibliography for the registered citations * @return the bibliography */ public Bibliography makeBibliography() { return makeBibliography(null); } /** * Generates a bibliography for the registered citations. Depending * on the selection mode selects, includes, or excludes bibliography * items whose fields and field values match the fields and field values * from the given example item data objects. * @param mode the selection mode * @param selection the example item data objects that contain * the fields and field values to match * @return the bibliography */ public Bibliography makeBibliography(SelectionMode mode, CSLItemData... selection) { return makeBibliography(mode, selection, null); } /** * <p>Generates a bibliography for the registered citations. Depending * on the selection mode selects, includes, or excludes bibliography * items whose fields and field values match the fields and field values * from the given example item data objects.</p> * <p>Note: This method will be deprecated in the next release.</p> * @param mode the selection mode * @param selection the example item data objects that contain * the fields and field values to match * @param quash regardless of the item data in {@code selection} * skip items if all fields/values from this list match * @return the bibliography */ public Bibliography makeBibliography(SelectionMode mode, CSLItemData[] selection, CSLItemData[] quash) { return makeBibliography(item -> { boolean include = true; if (selection != null) { switch (mode) { case INCLUDE: include = false; for (CSLItemData s : selection) { if (itemDataEqualsAny(item, s)) { include = true; break; } } break; case EXCLUDE: for (CSLItemData s : selection) { if (itemDataEqualsAny(item, s)) { include = false; break; } } break; case SELECT: for (CSLItemData s : selection) { if (!itemDataEqualsAny(item, s)) { include = false; break; } } break; } } if (include && quash != null) { boolean match = true; for (CSLItemData s : quash) { if (!itemDataEqualsAny(item, s)) { match = false; break; } } if (match) { include = false; } } return include; }); } /** * Generates a bibliography for registered citations * @param filter a function to apply to each registered citation item to * determine if it should be included in the bibliography or not (may * be {@code null} if all items should be included) * @return the bibliography */ public Bibliography makeBibliography(Predicate<CSLItemData> filter) { List<CSLItemData> filteredItems; if (filter == null) { filteredItems = sortedItems; } else { filteredItems = new ArrayList<>(); for (CSLItemData item : sortedItems) { if (filter.test(item)) { filteredItems.add(item); } } } List<String> entries = new ArrayList<>(); for (int i = 0; i < filteredItems.size(); i++) { CSLItemData item = filteredItems.get(i); RenderContext ctx = new RenderContext(style, locale, item, abbreviationProvider); style.getBibliography().render(ctx); if (!ctx.getResult().isEmpty()) { entries.add(outputFormat.formatBibliographyEntry(ctx, i)); } } return outputFormat.makeBibliography(entries.toArray(new String[0]), style.getBibliography()); } /** * Resets the processor's state */ public void reset() { outputFormat = new HtmlFormat(); convertLinks = false; registeredItems.clear(); sortedItems.clear(); generatedCitations.clear(); } /** * Creates an ad hoc bibliography from the given citation items using the * <code>"html"</code> output format. * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param items the citation items to add to the bibliography * @return the bibliography * @throws IOException if the underlying JavaScript files or the CSL style * could not be loaded * @see #makeAdhocBibliography(String, String, CSLItemData...) */ public static Bibliography makeAdhocBibliography(String style, CSLItemData... items) throws IOException { return makeAdhocBibliography(style, "html", items); } /** * Creates an ad hoc bibliography from the given citation items. * @param style the citation style to use. May either be a serialized * XML representation of the style or a style's name such as <code>ieee</code>. * In the latter case, the processor loads the style from the classpath (e.g. * <code>/ieee.csl</code>) * @param outputFormat the processor's output format (one of * <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>, * <code>"fo"</code>, or <code>"rtf"</code>) * @param items the citation items to add to the bibliography * @return the bibliography * @throws IOException if the CSL style could not be loaded */ public static Bibliography makeAdhocBibliography(String style, String outputFormat, CSLItemData... items) throws IOException { ItemDataProvider provider = new ListItemDataProvider(items); CSL csl = new CSL(provider, style); csl.setOutputFormat(outputFormat); String[] ids = new String[items.length]; for (int i = 0; i < items.length; ++i) { ids[i] = items[i].getId(); } csl.registerCitationItems(ids); return csl.makeBibliography(); } /** * Test if any of the attributes of {@code b} match the ones of {@code a}. * Note: This method will be deprecated in the next release * @param a the first object * @param b the object to match against * @return {@code true} if the match succeeds */ private static boolean itemDataEqualsAny(CSLItemData a, CSLItemData b) { if (a == b) { return true; } if (b == null) { return false; } if (b.getId() != null && Objects.equals(a.getId(), b.getId())) { return true; } if (b.getType() != null && Objects.equals(a.getType(), b.getType())) { return true; } if (b.getCategories() != null && Arrays.equals(a.getCategories(), b.getCategories())) { return true; } if (b.getLanguage() != null && Objects.equals(a.getLanguage(), b.getLanguage())) { return true; } if (b.getJournalAbbreviation() != null && Objects.equals(a.getJournalAbbreviation(), b.getJournalAbbreviation())) { return true; } if (b.getShortTitle() != null && Objects.equals(a.getShortTitle(), b.getShortTitle())) { return true; } if (b.getAuthor() != null && Arrays.equals(a.getAuthor(), b.getAuthor())) { return true; } if (b.getCollectionEditor() != null && Arrays.equals(a.getCollectionEditor(), b.getCollectionEditor())) { return true; } if (b.getComposer() != null && Arrays.equals(a.getComposer(), b.getComposer())) { return true; } if (b.getContainerAuthor() != null && Arrays.equals(a.getContainerAuthor(), b.getContainerAuthor())) { return true; } if (b.getDirector() != null && Arrays.equals(a.getDirector(), b.getDirector())) { return true; } if (b.getEditor() != null && Arrays.equals(a.getEditor(), b.getEditor())) { return true; } if (b.getEditorialDirector() != null && Arrays.equals(a.getEditorialDirector(), b.getEditorialDirector())) { return true; } if (b.getInterviewer() != null && Arrays.equals(a.getInterviewer(), b.getInterviewer())) { return true; } if (b.getIllustrator() != null && Arrays.equals(a.getIllustrator(), b.getIllustrator())) { return true; } if (b.getOriginalAuthor() != null && Arrays.equals(a.getOriginalAuthor(), b.getOriginalAuthor())) { return true; } if (b.getRecipient() != null && Arrays.equals(a.getRecipient(), b.getRecipient())) { return true; } if (b.getReviewedAuthor() != null && Arrays.equals(a.getReviewedAuthor(), b.getReviewedAuthor())) { return true; } if (b.getTranslator() != null && Arrays.equals(a.getTranslator(), b.getTranslator())) { return true; } if (b.getAccessed() != null && Objects.equals(a.getAccessed(), b.getAccessed())) { return true; } if (b.getContainer() != null && Objects.equals(a.getContainer(), b.getContainer())) { return true; } if (b.getEventDate() != null && Objects.equals(a.getEventDate(), b.getEventDate())) { return true; } if (b.getIssued() != null && Objects.equals(a.getIssued(), b.getIssued())) { return true; } if (b.getOriginalDate() != null && Objects.equals(a.getOriginalDate(), b.getOriginalDate())) { return true; } if (b.getSubmitted() != null && Objects.equals(a.getSubmitted(), b.getSubmitted())) { return true; } if (b.getAbstrct() != null && Objects.equals(a.getAbstrct(), b.getAbstrct())) { return true; } if (b.getAnnote() != null && Objects.equals(a.getAnnote(), b.getAnnote())) { return true; } if (b.getArchive() != null && Objects.equals(a.getArchive(), b.getArchive())) { return true; } if (b.getArchiveLocation() != null && Objects.equals(a.getArchiveLocation(), b.getArchiveLocation())) { return true; } if (b.getArchivePlace() != null && Objects.equals(a.getArchivePlace(), b.getArchivePlace())) { return true; } if (b.getAuthority() != null && Objects.equals(a.getAuthority(), b.getAuthority())) { return true; } if (b.getCallNumber() != null && Objects.equals(a.getCallNumber(), b.getCallNumber())) { return true; } if (b.getChapterNumber() != null && Objects.equals(a.getChapterNumber(), b.getChapterNumber())) { return true; } if (b.getCitationNumber() != null && Objects.equals(a.getCitationNumber(), b.getCitationNumber())) { return true; } if (b.getCitationLabel() != null && Objects.equals(a.getCitationLabel(), b.getCitationLabel())) { return true; } if (b.getCollectionNumber() != null && Objects.equals(a.getCollectionNumber(), b.getCollectionNumber())) { return true; } if (b.getCollectionTitle() != null && Objects.equals(a.getCollectionTitle(), b.getCollectionTitle())) { return true; } if (b.getContainerTitle() != null && Objects.equals(a.getContainerTitle(), b.getContainerTitle())) { return true; } if (b.getContainerTitleShort() != null && Objects.equals(a.getContainerTitleShort(), b.getContainerTitleShort())) { return true; } if (b.getDimensions() != null && Objects.equals(a.getDimensions(), b.getDimensions())) { return true; } if (b.getDOI() != null && Objects.equals(a.getDOI(), b.getDOI())) { return true; } if (b.getEdition() != null && Objects.equals(a.getEdition(), b.getEdition())) { return true; } if (b.getEvent() != null && Objects.equals(a.getEvent(), b.getEvent())) { return true; } if (b.getEventPlace() != null && Objects.equals(a.getEventPlace(), b.getEventPlace())) { return true; } if (b.getFirstReferenceNoteNumber() != null && Objects.equals(a.getFirstReferenceNoteNumber(), b.getFirstReferenceNoteNumber())) { return true; } if (b.getGenre() != null && Objects.equals(a.getGenre(), b.getGenre())) { return true; } if (b.getISBN() != null && Objects.equals(a.getISBN(), b.getISBN())) { return true; } if (b.getISSN() != null && Objects.equals(a.getISSN(), b.getISSN())) { return true; } if (b.getIssue() != null && Objects.equals(a.getIssue(), b.getIssue())) { return true; } if (b.getJurisdiction() != null && Objects.equals(a.getJurisdiction(), b.getJurisdiction())) { return true; } if (b.getKeyword() != null && Objects.equals(a.getKeyword(), b.getKeyword())) { return true; } if (b.getLocator() != null && Objects.equals(a.getLocator(), b.getLocator())) { return true; } if (b.getMedium() != null && Objects.equals(a.getMedium(), b.getMedium())) { return true; } if (b.getNote() != null && Objects.equals(a.getNote(), b.getNote())) { return true; } if (b.getNumber() != null && Objects.equals(a.getNumber(), b.getNumber())) { return true; } if (b.getNumberOfPages() != null && Objects.equals(a.getNumberOfPages(), b.getNumberOfPages())) { return true; } if (b.getNumberOfVolumes() != null && Objects.equals(a.getNumberOfVolumes(), b.getNumberOfVolumes())) { return true; } if (b.getOriginalPublisher() != null && Objects.equals(a.getOriginalPublisher(), b.getOriginalPublisher())) { return true; } if (b.getOriginalPublisherPlace() != null && Objects.equals(a.getOriginalPublisherPlace(), b.getOriginalPublisherPlace())) { return true; } if (b.getOriginalTitle() != null && Objects.equals(a.getOriginalTitle(), b.getOriginalTitle())) { return true; } if (b.getPage() != null && Objects.equals(a.getPage(), b.getPage())) { return true; } if (b.getPageFirst() != null && Objects.equals(a.getPageFirst(), b.getPageFirst())) { return true; } if (b.getPMCID() != null && Objects.equals(a.getPMCID(), b.getPMCID())) { return true; } if (b.getPMID() != null && Objects.equals(a.getPMID(), b.getPMID())) { return true; } if (b.getPublisher() != null && Objects.equals(a.getPublisher(), b.getPublisher())) { return true; } if (b.getPublisherPlace() != null && Objects.equals(a.getPublisherPlace(), b.getPublisherPlace())) { return true; } if (b.getReferences() != null && Objects.equals(a.getReferences(), b.getReferences())) { return true; } if (b.getReviewedTitle() != null && Objects.equals(a.getReviewedTitle(), b.getReviewedTitle())) { return true; } if (b.getScale() != null && Objects.equals(a.getScale(), b.getScale())) { return true; } if (b.getSection() != null && Objects.equals(a.getSection(), b.getSection())) { return true; } if (b.getSource() != null && Objects.equals(a.getSource(), b.getSource())) { return true; } if (b.getStatus() != null && Objects.equals(a.getStatus(), b.getStatus())) { return true; } if (b.getTitle() != null && Objects.equals(a.getTitle(), b.getTitle())) { return true; } if (b.getTitleShort() != null && Objects.equals(a.getTitleShort(), b.getTitleShort())) { return true; } if (b.getURL() != null && Objects.equals(a.getURL(), b.getURL())) { return true; } if (b.getVersion() != null && Objects.equals(a.getVersion(), b.getVersion())) { return true; } if (b.getVolume() != null && Objects.equals(a.getVolume(), b.getVolume())) { return true; } return b.getYearSuffix() != null && Objects.equals(a.getYearSuffix(), b.getYearSuffix()); } }
Fix javadoc
citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java
Fix javadoc
<ide><path>iteproc-java/src/main/java/de/undercouch/citeproc/CSL.java <ide> private final ItemDataProvider itemDataProvider; <ide> <ide> /** <del> * An object that provides abbreviations (may be {@link null}) <add> * An object that provides abbreviations (may be {@code null}) <ide> */ <ide> private final AbbreviationProvider abbreviationProvider; <ide> <ide> * @param itemDataProvider an object that provides citation item data <ide> * @param localeProvider an object that provides CSL locales <ide> * @param abbreviationProvider an object that provides abbreviations <del> * (may be {@link null}) <add> * (may be {@code null}) <ide> * @param style the citation style to use. May either be a serialized <ide> * XML representation of the style or a style's name such as <code>ieee</code>. <ide> * In the latter case, the processor loads the style from the classpath (e.g.
Java
apache-2.0
5e14712b93f26d0c23e20361a1f402e6bb3d84b3
0
mrniko/redisson,redisson/redisson
package org.redisson; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Rui Gu (https://github.com/jackygurui) */ public class RedisVersion implements Comparable<RedisVersion>{ private final String fullVersion; private final Integer majorVersion; private final Integer minorVersion; private final Integer patchVersion; public RedisVersion(String fullVersion) { this.fullVersion = fullVersion; Matcher matcher = Pattern.compile("^([\\d]+)\\.([\\d]+)\\.([\\d]+)").matcher(fullVersion); matcher.find(); majorVersion = Integer.parseInt(matcher.group(1)); minorVersion = Integer.parseInt(matcher.group(2)); patchVersion = Integer.parseInt(matcher.group(3)); } public String getFullVersion() { return fullVersion; } public int getMajorVersion() { return majorVersion; } public int getMinorVersion() { return minorVersion; } public int getPatchVersion() { return patchVersion; } @Override public int compareTo(RedisVersion o) { int ma = this.majorVersion.compareTo(o.majorVersion); int mi = this.minorVersion.compareTo(o.minorVersion); int pa = this.patchVersion.compareTo(o.patchVersion); return ma != 0 ? ma : mi != 0 ? mi : pa; } public int compareTo(String redisVersion) { return this.compareTo(new RedisVersion(redisVersion)); } public static int compareTo(String redisVersion1, String redisVersion2) { return new RedisVersion(redisVersion1).compareTo(redisVersion2); } }
redisson/src/test/java/org/redisson/RedisVersion.java
package org.redisson; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Rui Gu (https://github.com/jackygurui) */ public class RedisVersion implements Comparable<RedisVersion>{ private final String fullVersion; private final Integer majorVersion; private final Integer minorVersion; private final Integer patchVersion; public RedisVersion(String fullVersion) { this.fullVersion = fullVersion; Matcher matcher = Pattern.compile("^([\\d]+)\\.([\\d]+)\\.([\\d]+)$").matcher(fullVersion); matcher.find(); majorVersion = Integer.parseInt(matcher.group(1)); minorVersion = Integer.parseInt(matcher.group(2)); patchVersion = Integer.parseInt(matcher.group(3)); } public String getFullVersion() { return fullVersion; } public int getMajorVersion() { return majorVersion; } public int getMinorVersion() { return minorVersion; } public int getPatchVersion() { return patchVersion; } @Override public int compareTo(RedisVersion o) { int ma = this.majorVersion.compareTo(o.majorVersion); int mi = this.minorVersion.compareTo(o.minorVersion); int pa = this.patchVersion.compareTo(o.patchVersion); return ma != 0 ? ma : mi != 0 ? mi : pa; } public int compareTo(String redisVersion) { return this.compareTo(new RedisVersion(redisVersion)); } public static int compareTo(String redisVersion1, String redisVersion2) { return new RedisVersion(redisVersion1).compareTo(redisVersion2); } }
Redis version parsing fixed
redisson/src/test/java/org/redisson/RedisVersion.java
Redis version parsing fixed
<ide><path>edisson/src/test/java/org/redisson/RedisVersion.java <ide> <ide> public RedisVersion(String fullVersion) { <ide> this.fullVersion = fullVersion; <del> Matcher matcher = Pattern.compile("^([\\d]+)\\.([\\d]+)\\.([\\d]+)$").matcher(fullVersion); <add> Matcher matcher = Pattern.compile("^([\\d]+)\\.([\\d]+)\\.([\\d]+)").matcher(fullVersion); <ide> matcher.find(); <ide> majorVersion = Integer.parseInt(matcher.group(1)); <ide> minorVersion = Integer.parseInt(matcher.group(2));
Java
mit
b3e5e0872741b9e297809fcdcac33c838a9f127b
0
ade2/AdePlugin,ade/AdePlugin
package se.ade.minecraft.adeplugin; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.plugin.java.JavaPlugin; import se.ade.minecraft.adeplugin.db.DbConnection; import se.ade.minecraft.adeplugin.infrastructure.SubModule; import se.ade.minecraft.adeplugin.warpstone.WarpStoneModule; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; /** * Adrian Nilsson * Created 2013-12-27 23:07 */ public class AdePlugin extends JavaPlugin { public static final String CONFIG_FILE = "plugins/adeplugin.yml"; private static AdePlugin instance; private DbConnection dbConnection; private SubModule[] activeModules; public AdePlugin() { if(instance != null) { throw new RuntimeException("Instance already set"); } instance = this; } public static AdePlugin get() { return instance; } @Override public void onEnable() { try { getConfig().options().copyDefaults(true); getConfig().load(CONFIG_FILE); } catch (Exception e) { getLogger().warning("Couldn't open " + CONFIG_FILE + " config file. Using default values. Looking for the file in " + System.getProperty("user.dir") + "\\" + CONFIG_FILE); e.printStackTrace(); } dbConnection = new DbConnection(this); dbConnection.connect(); activeModules = new SubModule[] { new WarpStoneModule() //new BlueprintModule() }; for(SubModule subModule : activeModules) { subModule.onEnable(this); } if(isDevMode()) { getLogger().warning("Development mode is enabled."); } } public boolean isDevMode() { return getConfig().getBoolean("development_mode"); } @Override public void onDisable() { for(SubModule subModule : activeModules) { subModule.onDisable(); } activeModules = null; instance = null; } public void removeRecipe(ShapedRecipe itemRecipe){ Iterator<Recipe> recipeIterator = getServer().recipeIterator(); StringBuilder iteratedRecipeString = new StringBuilder(); StringBuilder itemRecipeString = new StringBuilder(); int matches = 0; //Create a recipe string to match with Map<Character, ItemStack> soughtIngredients = itemRecipe.getIngredientMap(); String[] itemIngredients = itemRecipe.getShape(); for(int i = 0; i <itemIngredients.length; i++) { itemRecipeString.append(itemIngredients[i]).append(","); } while(recipeIterator.hasNext()){ Recipe currentRecipe = recipeIterator.next(); if(currentRecipe instanceof ShapedRecipe){ ShapedRecipe currentShapedRecipe = (ShapedRecipe) currentRecipe; Map<Character, ItemStack> currentIngredients = currentShapedRecipe.getIngredientMap(); if(currentIngredients.values().containsAll(soughtIngredients.values())){ if(currentRecipe.getResult().getType() == itemRecipe.getResult().getType()) { //Ingredients and output type matches. Assume this is the recipe. recipeIterator.remove(); //getLogger().info("Recipe removed (result item type: " + currentRecipe.getResult().getType().name() + ")."); matches++; } } } } if(matches == 0) { getLogger().warning("Failed to remove recipe (result item type: " + itemRecipe.getResult().getType().name() + ")."); } } public DbConnection getDbConnection() { return dbConnection; } public void debugLog(String s) { if(isDevMode()) { getLogger().log(Level.INFO, s); } } }
src/main/java/se/ade/minecraft/adeplugin/AdePlugin.java
package se.ade.minecraft.adeplugin; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.plugin.java.JavaPlugin; import se.ade.minecraft.adeplugin.db.DbConnection; import se.ade.minecraft.adeplugin.infrastructure.SubModule; import se.ade.minecraft.adeplugin.warpstone.WarpStoneModule; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; /** * Adrian Nilsson * Created 2013-12-27 23:07 */ public class AdePlugin extends JavaPlugin { public static final String CONFIG_FILE = "plugins\\adeplugin.yml"; private static AdePlugin instance; private DbConnection dbConnection; private SubModule[] activeModules; public AdePlugin() { if(instance != null) { throw new RuntimeException("Instance already set"); } instance = this; } public static AdePlugin get() { return instance; } @Override public void onEnable() { try { getConfig().options().copyDefaults(true); getConfig().load(CONFIG_FILE); } catch (Exception e) { getLogger().warning("Couldn't open " + CONFIG_FILE + " config file. Using default values. Looking for the file in " + System.getProperty("user.dir") + "\\" + CONFIG_FILE); e.printStackTrace(); } dbConnection = new DbConnection(this); dbConnection.connect(); activeModules = new SubModule[] { new WarpStoneModule() //new BlueprintModule() }; for(SubModule subModule : activeModules) { subModule.onEnable(this); } if(isDevMode()) { getLogger().warning("Development mode is enabled."); } } public boolean isDevMode() { return getConfig().getBoolean("development_mode"); } @Override public void onDisable() { for(SubModule subModule : activeModules) { subModule.onDisable(); } activeModules = null; instance = null; } public void removeRecipe(ShapedRecipe itemRecipe){ Iterator<Recipe> recipeIterator = getServer().recipeIterator(); StringBuilder iteratedRecipeString = new StringBuilder(); StringBuilder itemRecipeString = new StringBuilder(); int matches = 0; //Create a recipe string to match with Map<Character, ItemStack> soughtIngredients = itemRecipe.getIngredientMap(); String[] itemIngredients = itemRecipe.getShape(); for(int i = 0; i <itemIngredients.length; i++) { itemRecipeString.append(itemIngredients[i]).append(","); } while(recipeIterator.hasNext()){ Recipe currentRecipe = recipeIterator.next(); if(currentRecipe instanceof ShapedRecipe){ ShapedRecipe currentShapedRecipe = (ShapedRecipe) currentRecipe; Map<Character, ItemStack> currentIngredients = currentShapedRecipe.getIngredientMap(); if(currentIngredients.values().containsAll(soughtIngredients.values())){ if(currentRecipe.getResult().getType() == itemRecipe.getResult().getType()) { //Ingredients and output type matches. Assume this is the recipe. recipeIterator.remove(); //getLogger().info("Recipe removed (result item type: " + currentRecipe.getResult().getType().name() + ")."); matches++; } } } } if(matches == 0) { getLogger().warning("Failed to remove recipe (result item type: " + itemRecipe.getResult().getType().name() + ")."); } } public DbConnection getDbConnection() { return dbConnection; } public void debugLog(String s) { if(isDevMode()) { getLogger().log(Level.INFO, s); } } }
Forward slash in config file location
src/main/java/se/ade/minecraft/adeplugin/AdePlugin.java
Forward slash in config file location
<ide><path>rc/main/java/se/ade/minecraft/adeplugin/AdePlugin.java <ide> * Created 2013-12-27 23:07 <ide> */ <ide> public class AdePlugin extends JavaPlugin { <del> public static final String CONFIG_FILE = "plugins\\adeplugin.yml"; <add> public static final String CONFIG_FILE = "plugins/adeplugin.yml"; <ide> <ide> private static AdePlugin instance; <ide> private DbConnection dbConnection;
Java
apache-2.0
01aeff252954737a2cc16756c34215788332b36e
0
DataSketches/sketches-core
/* * 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.datasketches.hll; import static org.apache.datasketches.Util.invPow2; import static org.apache.datasketches.hll.HllUtil.EMPTY; import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; import static org.apache.datasketches.hll.TgtHllType.HLL_8; import org.apache.datasketches.SketchesArgumentException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableMemory; /** * This performs union operations for all HllSketches. This union operator can be configured to be * on or off heap. The source sketch given to this union using the {@link #update(HllSketch)} can * be configured with any precision value <i>lgConfigK</i> (from 4 to 21), any <i>TgtHllType</i> * (HLL_4, HLL_6, HLL_8), and either on or off-heap; and it can be in either of the sparse modes * (<i>LIST</i> or <i>SET</i>), or the dense mode (<i>HLL</i>). * * <p>Although the API for this union operator parallels many of the methods of the * <i>HllSketch</i>, the behavior of the union operator has some fundamental differences.</p> * * <p>First, this union operator is configured with a <i>lgMaxK</i> instead of the normal * <i>lgConfigK</i>. Generally, this union operator will inherit the lowest <i>lgConfigK</i> * less than <i>lgMaxK</i> that it has seen. However, the <i>lgConfigK</i> of incoming sketches that * are still in sparse are ignored. The <i>lgMaxK</i> provides the user the ability to specify the * largest maximum size for the union operation. * * <p>Second, the user cannot specify the {@link TgtHllType} as an input parameter to the union. * Instead, it is specified for the sketch returned with {@link #getResult(TgtHllType)}. * * @author Lee Rhodes * @author Kevin Lang */ public class Union extends BaseHllSketch { final int lgMaxK; private final HllSketch gadget; /** * Construct this Union operator with the default maximum log-base-2 of <i>K</i>. */ public Union() { lgMaxK = HllSketch.DEFAULT_LG_K; gadget = new HllSketch(lgMaxK, HLL_8); } /** * Construct this Union operator with a given maximum log-base-2 of <i>K</i>. * @param lgMaxK the desired maximum log-base-2 of <i>K</i>. This value must be * between 4 and 21 inclusively. */ public Union(final int lgMaxK) { this.lgMaxK = HllUtil.checkLgK(lgMaxK); gadget = new HllSketch(lgMaxK, HLL_8); } /** * Construct this Union operator with a given maximum log-base-2 of <i>K</i> and the given * WritableMemory as the destination for this Union. This WritableMemory is usually configured * for off-heap memory. What remains on the java heap is a thin wrapper object that reads and * writes to the given WritableMemory. * * <p>The given <i>dstMem</i> is checked for the required capacity as determined by * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}. * @param lgMaxK the desired maximum log-base-2 of <i>K</i>. This value must be * between 4 and 21 inclusively. * @param dstWmem the destination writable memory for the sketch. */ public Union(final int lgMaxK, final WritableMemory dstWmem) { this.lgMaxK = HllUtil.checkLgK(lgMaxK); gadget = new HllSketch(lgMaxK, HLL_8, dstWmem); } //used only by writableWrap private Union(final HllSketch sketch) { lgMaxK = sketch.getLgConfigK(); gadget = sketch; } /** * Construct a union operator populated with the given byte array image of an HllSketch. * @param byteArray the given byte array * @return a union operator populated with the given byte array image of an HllSketch. */ public static final Union heapify(final byte[] byteArray) { return heapify(Memory.wrap(byteArray)); } /** * Construct a union operator populated with the given Memory image of an HllSketch. * @param mem the given Memory * @return a union operator populated with the given Memory image of an HllSketch. */ public static final Union heapify(final Memory mem) { final int lgK = HllUtil.checkLgK(mem.getByte(PreambleUtil.LG_K_BYTE)); final HllSketch sk = HllSketch.heapify(mem, false); //allows non-finalized image final Union union = new Union(lgK); union.update(sk); return union; } /** * Wraps the given WritableMemory, which must be a image of a valid updatable HLL_8 sketch, * and may have data. What remains on the java heap is a * thin wrapper object that reads and writes to the given WritableMemory, which, depending on * how the user configures the WritableMemory, may actually reside on the Java heap or off-heap. * * <p>The given <i>dstMem</i> is checked for the required capacity as determined by * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}, and for the correct type. * @param srcWmem an writable image of a valid sketch with data. * @return a Union operator where the sketch data is in the given dstMem. */ public static final Union writableWrap(final WritableMemory srcWmem) { final TgtHllType tgtHllType = extractTgtHllType(srcWmem); if (tgtHllType != TgtHllType.HLL_8) { throw new SketchesArgumentException( "Union can only wrap writable HLL_8 sketches that were the Gadget of a Union."); } //allows writableWrap of non-finalized image return new Union(HllSketch.writableWrap(srcWmem, false)); } @Override public double getCompositeEstimate() { checkRebuildCurMinNumKxQ(gadget); return gadget.hllSketchImpl.getCompositeEstimate(); } @Override CurMode getCurMode() { return gadget.getCurMode(); } @Override public int getCompactSerializationBytes() { return gadget.getCompactSerializationBytes(); } @Override public double getEstimate() { checkRebuildCurMinNumKxQ(gadget); return gadget.getEstimate(); } /** * Gets the effective <i>lgConfigK</i> for the union operator, which may be less than * <i>lgMaxK</i>. * @return the <i>lgConfigK</i>. */ @Override public int getLgConfigK() { return gadget.getLgConfigK(); } @Override public double getLowerBound(final int numStdDev) { checkRebuildCurMinNumKxQ(gadget); return gadget.getLowerBound(numStdDev); } /** * Returns the maximum size in bytes that this union operator can grow to given a lgK. * * @param lgK The maximum Log2 of K for this union operator. This value must be * between 4 and 21 inclusively. * @return the maximum size in bytes that this union operator can grow to. */ public static int getMaxSerializationBytes(final int lgK) { return HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_8); } /** * Return the result of this union operator as an HLL_4 sketch. * @return the result of this union operator as an HLL_4 sketch. */ public HllSketch getResult() { return getResult(HllSketch.DEFAULT_HLL_TYPE); } /** * Return the result of this union operator with the specified {@link TgtHllType} * @param tgtHllType the TgtHllType enum * @return the result of this union operator with the specified TgtHllType */ public HllSketch getResult(final TgtHllType tgtHllType) { checkRebuildCurMinNumKxQ(gadget); return gadget.copyAs(tgtHllType); } @Override public TgtHllType getTgtHllType() { return TgtHllType.HLL_8; } @Override public int getUpdatableSerializationBytes() { return gadget.getUpdatableSerializationBytes(); } @Override public double getUpperBound(final int numStdDev) { checkRebuildCurMinNumKxQ(gadget); return gadget.getUpperBound(numStdDev); } @Override public boolean isCompact() { return gadget.isCompact(); } @Override public boolean isEmpty() { return gadget.isEmpty(); } @Override public boolean isMemory() { return gadget.isMemory(); } @Override public boolean isOffHeap() { return gadget.isOffHeap(); } @Override boolean isOutOfOrder() { return gadget.isOutOfOrder(); } @Override public boolean isSameResource(final Memory mem) { return gadget.isSameResource(mem); } boolean isRebuildCurMinNumKxQFlag() { return gadget.hllSketchImpl.isRebuildCurMinNumKxQFlag(); } void putRebuildCurMinNumKxQFlag(final boolean rebuild) { gadget.hllSketchImpl.putRebuildCurMinNumKxQFlag(rebuild); } /** * Resets to empty and retains the current lgK, but does not change the configured value of * lgMaxK. */ @Override public void reset() { gadget.reset(); } /** * Gets the serialization of this union operator as a byte array in compact form, which is * designed to be heapified only. It is not directly updatable. * For the Union operator, this is the serialization of the internal state of * the union operator as a sketch. * @return the serialization of this union operator as a byte array. */ @Override public byte[] toCompactByteArray() { checkRebuildCurMinNumKxQ(gadget); return gadget.toCompactByteArray(); } @Override public byte[] toUpdatableByteArray() { checkRebuildCurMinNumKxQ(gadget); return gadget.toUpdatableByteArray(); } @Override public String toString(final boolean summary, final boolean hllDetail, final boolean auxDetail, final boolean all) { checkRebuildCurMinNumKxQ(gadget); return gadget.toString(summary, hllDetail, auxDetail, all); } /** * Update this union operator with the given sketch. * @param sketch the given sketch. */ public void update(final HllSketch sketch) { gadget.hllSketchImpl = unionImpl(sketch, gadget, lgMaxK); } @Override void couponUpdate(final int coupon) { if (coupon == EMPTY) { return; } gadget.hllSketchImpl = gadget.hllSketchImpl.couponUpdate(coupon); } // Union operator logic /** * Union the given source and destination sketches. This static method examines the state of * the current internal gadget and the incoming sketch and determines the optimum way to * perform the union. This may involve swapping the merge order, downsampling, transforming, * and / or copying one of the arguments and may completely replace the internals of the union. * * <p>If the union gadget is empty, the source sketch is effectively copied to the union gadget * after any required transformations. * * <p>The direction of the merge is reversed if the union gadget is in LIST or SET mode, and the * source sketch is in HLL mode. This is done to maintain maximum accuracy of the union process. * * <p>The source sketch is downsampled if the source LgK is larger than maxLgK and in HLL mode. * * <p>The union gadget is downsampled if both source and union gadget are in HLL mode * and the source LgK <b>less than</b> the union gadget LgK. * * @param source the given incoming sketch, which cannot be modified. * @param gadget the given gadget sketch, which has a target of HLL_8 and holds the result. * @param lgMaxK the maximum value of log2 K for this union. * @return the union of the two sketches in the form of the internal HllSketchImpl, which is * always in HLL_8 form. */ private static HllSketchImpl unionImpl(final HllSketch source, final HllSketch gadget, final int lgMaxK) { assert gadget.getTgtHllType() == HLL_8; if ((source == null) || source.isEmpty()) { return gadget.hllSketchImpl; } final CurMode srcMode = source.getCurMode(); if (srcMode == CurMode.LIST ) { source.mergeTo(gadget); return gadget.hllSketchImpl; } final int srcLgK = source.getLgConfigK(); final int gadgetLgK = gadget.getLgConfigK(); final boolean srcIsMem = source.isMemory(); final boolean gdtIsMem = gadget.isMemory(); final boolean gdtEmpty = gadget.isEmpty(); if (srcMode == CurMode.SET ) { if (gdtEmpty && (srcLgK == gadgetLgK) && (!srcIsMem) && (!gdtIsMem)) { gadget.hllSketchImpl = source.copyAs(HLL_8).hllSketchImpl; return gadget.hllSketchImpl; } source.mergeTo(gadget); return gadget.hllSketchImpl; } //Hereafter, the source is in HLL mode. final int bit0 = gdtIsMem ? 1 : 0; final int bits1_2 = (gdtEmpty ? 3 : gadget.getCurMode().ordinal()) << 1; final int bit3 = (srcLgK < gadgetLgK) ? 8 : 0; final int bit4 = (srcLgK > lgMaxK) ? 16 : 0; final int sw = bit4 | bit3 | bits1_2 | bit0; HllSketchImpl hllSketchImpl = null; //never returned as null switch (sw) { case 0: //src <= max, src >= gdt, gdtLIST, gdtHeap case 8: //src <= max, src < gdt, gdtLIST, gdtHeap case 2: //src <= max, src >= gdt, gdtSET, gdtHeap case 10://src <= max, src < gdt, gdtSET, gdtHeap { //Action: copy src, reverse merge w/autofold, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 16://src > max, src >= gdt, gdtList, gdtHeap case 18://src > max, src >= gdt, gdtSet, gdtHeap { //Action: downsample src to MaxLgK, reverse merge w/autofold, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 1: //src <= max, src >= gdt, gdtLIST, gdtMemory case 9: //src <= max, src < gdt, gdtLIST, gdtMemory case 3: //src <= max, src >= gdt, gdtSET, gdtMemory case 11://src <= max, src < gdt, gdtSET, gdtMemory { //Action: copy src, reverse merge w/autofold, use gdt memory, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,mem,list/set) -> src(Hll8,heap,hll) hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 17://src > max, src >= gdt, gdtList, gdtMemory case 19://src > max, src >= gdt, gdtSet, gdtMemory { //Action: downsample src to MaxLgK, reverse merge w/autofold, use gdt memory, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,mem,list/set) -> src(Hll8,heap,hll), autofold hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 4: //src <= max, src >= gdt, gdtHLL, gdtHeap case 20://src > max, src >= gdt, gdtHLL, gdtHeap case 5: //src <= max, src >= gdt, gdtHLL, gdtMemory case 21://src > max, src >= gdt, gdtHLL, gdtMemory { //Action: forward HLL merge w/autofold, ooof=True //merge src(Hll4,6,8,heap/mem,Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) mergeHlltoHLLmode(source, gadget, srcLgK, gadgetLgK, srcIsMem, gdtIsMem); hllSketchImpl = gadget.putOutOfOrderFlag(true).hllSketchImpl; break; } case 12://src <= max, src < gdt, gdtHLL, gdtHeap { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, ooof=True final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); //merge src(Hll4,6,8;heap/mem,Mode=HLL) -> gdt(Hll8,heap,hll) mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcIsMem, false); hllSketchImpl = gdtHll8Heap.putOutOfOrderFlag(true).hllSketchImpl; break; } case 13://src <= max, src < gdt, gdtHLL, gdtMemory { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, use gdt memory, ooof=True final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); //merge src(Hll4,6,8;heap/mem;Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcIsMem, false); hllSketchImpl = useGadgetMemory(gadget, gdtHll8Heap, true).hllSketchImpl; break; } case 6: //src <= max, src >= gdt, gdtEmpty, gdtHeap case 14://src <= max, src < gdt, gdtEmpty, gdtHeap { //Action: copy src, replace gdt, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 22://src > max, src >= gdt, gdtEmpty, gdtHeap { //Action: downsample src to lgMaxK, replace gdt, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 7: //src <= max, src >= gdt, gdtEmpty, gdtMemory case 15://src <= max, src < gdt, gdtEmpty, gdtMemory { //Action: copy src, use gdt memory, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 23://src > max, src >= gdt, gdtEmpty, gdtMemory, replace mem, downsample src, ooof=src { //Action: downsample src to lgMaxK, use gdt memory, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } //default: return gadget.hllSketchImpl; //not possible } return hllSketchImpl; } private static final HllSketch useGadgetMemory( final HllSketch gadget, final HllSketch hll8Heap, final boolean setOooFlag) { final WritableMemory wmem = gadget.getWritableMemory(); //use the gdt wmem final byte[] byteArr = hll8Heap.toUpdatableByteArray(); //serialize srcCopy wmem.putByteArray(0, byteArr, 0, byteArr.length); //replace old data with new return (setOooFlag) ? HllSketch.writableWrap(wmem, false).putOutOfOrderFlag(true) //wrap, set oooflag, return : HllSketch.writableWrap(wmem, false); //wrap & return } private static final void mergeHlltoHLLmode(final HllSketch src, final HllSketch tgt, final int srcLgK, final int tgtLgK, final boolean srcIsMem, final boolean tgtIsMem) { final int sw = (tgtIsMem ? 1 : 0) | (srcIsMem ? 2 : 0) | ((srcLgK > tgtLgK) ? 4 : 0) | ((src.getTgtHllType() != HLL_8) ? 8 : 0); switch (sw) { case 0: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=heap final int srcK = 1 << srcLgK; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final byte tgtV = tgtArr[i]; tgtArr[i] = (srcV > tgtV) ? srcV : tgtV; } break; } case 1: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=mem final int srcK = 1 << srcLgK; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + i); tgtMem.putByte(HLL_BYTE_ARR_START + i, (srcV > tgtV) ? srcV : tgtV); } break; } case 2: { //HLL_8, srcLgK=tgtLgK, src=mem, tgt=heap final int srcK = 1 << srcLgK; final Memory srcMem = src.getMemory(); final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final byte tgtV = tgtArr[i]; tgtArr[i] = (srcV > tgtV) ? srcV : tgtV; } break; } case 3: { //HLL_8, srcLgK=tgtLgK, src=mem, tgt=mem final int srcK = 1 << srcLgK; final Memory srcMem = src.getMemory(); final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + i); tgtMem.putByte(HLL_BYTE_ARR_START + i, (srcV > tgtV) ? srcV : tgtV); } break; } case 4: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=heap final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final int j = i & tgtKmask; final byte tgtV = tgtArr[j]; tgtArr[j] = (srcV > tgtV) ? srcV : tgtV; } break; } case 5: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final int j = i & tgtKmask; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + j); tgtMem.putByte(HLL_BYTE_ARR_START + j, (srcV > tgtV) ? srcV : tgtV); } break; } case 6: { //HLL_8, srcLgK>tgtLgK, src=mem, tgt=heap final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final Memory srcMem = src.getMemory(); final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final int j = i & tgtKmask; final byte tgtV = tgtArr[j]; tgtArr[j] = (srcV > tgtV) ? srcV : tgtV; } break; } case 7: { //HLL_8, srcLgK>tgtLgK, src=mem, tgt=mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final Memory srcMem = src.getMemory(); final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final int j = i & tgtKmask; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + j); tgtMem.putByte(HLL_BYTE_ARR_START + j, (srcV > tgtV) ? srcV : tgtV); } break; } case 8: case 9: case 10: case 11: { //!HLL_8, srcLgK=tgtLgK, src=heap/mem, tgt=heap/mem final int srcK = 1 << srcLgK; final AbstractHllArray srcAbsHllArr = (AbstractHllArray)(src.hllSketchImpl); final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); for (int i = 0; i < srcK; i++) { final int srcV = srcAbsHllArr.getSlotValue(i); tgtAbsHllArr.updateSlotNoKxQ(i, srcV); } break; } case 12: case 13: case 14: case 15: { //!HLL_8, srcLgK>tgtLgK, src=heap/mem, tgt=heap/mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final AbstractHllArray srcAbsHllArr = (AbstractHllArray)(src.hllSketchImpl); final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); for (int i = 0; i < srcK; i++) { final int srcV = srcAbsHllArr.getSlotValue(i); final int j = i & tgtKmask; tgtAbsHllArr.updateSlotNoKxQ(j, srcV); } break; } } tgt.hllSketchImpl.putRebuildCurMinNumKxQFlag(true); } //Used by union operator. Always copies or downsamples to Heap HLL_8. //Caller must ultimately manage oooFlag, as caller has more context. /** * Copies or downsamples the given candidate HLLmode sketch to tgtLgK, HLL_8, on the heap. * * @param candidate the HllSketch to downsample, must be in HLL mode. * @param tgtLgK the LgK to downsample to. * @return the downsampled HllSketch. */ private static final HllSketch downsample(final HllSketch candidate, final int tgtLgK) { final AbstractHllArray candArr = (AbstractHllArray) candidate.hllSketchImpl; final HllArray tgtHllArr = HllArray.newHeapHll(tgtLgK, TgtHllType.HLL_8); final PairIterator candItr = candArr.iterator(); while (candItr.nextValid()) { tgtHllArr.couponUpdate(candItr.getPair()); //rebuilds KxQ, etc. } //both of these are required for isomorphism tgtHllArr.putHipAccum(candArr.getHipAccum()); tgtHllArr.putOutOfOrder(candidate.isOutOfOrder()); tgtHllArr.putRebuildCurMinNumKxQFlag(false); return new HllSketch(tgtHllArr); } //Used to rebuild curMin, numAtCurMin and KxQ registers, due to high performance merge operation static final void checkRebuildCurMinNumKxQ(final HllSketch sketch) { final HllSketchImpl hllSketchImpl = sketch.hllSketchImpl; final CurMode curMode = sketch.getCurMode(); final TgtHllType tgtHllType = sketch.getTgtHllType(); final boolean rebuild = hllSketchImpl.isRebuildCurMinNumKxQFlag(); if ( !rebuild || (curMode != CurMode.HLL) || (tgtHllType != HLL_8) ) { return; } final AbstractHllArray absHllArr = (AbstractHllArray)(hllSketchImpl); int curMin = 64; int numAtCurMin = 0; double kxq0 = 1 << absHllArr.getLgConfigK(); double kxq1 = 0; final PairIterator itr = absHllArr.iterator(); while (itr.nextAll()) { final int v = itr.getValue(); if (v > 0) { if (v < 32) { kxq0 += invPow2(v) - 1.0; } else { kxq1 += invPow2(v) - 1.0; } } if (v > curMin) { continue; } if (v < curMin) { curMin = v; numAtCurMin = 1; } else { numAtCurMin++; } } absHllArr.putKxQ0(kxq0); absHllArr.putKxQ1(kxq1); absHllArr.putCurMin(curMin); absHllArr.putNumAtCurMin(numAtCurMin); absHllArr.putRebuildCurMinNumKxQFlag(false); //HipAccum is not affected } }
src/main/java/org/apache/datasketches/hll/Union.java
/* * 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.datasketches.hll; import static org.apache.datasketches.Util.invPow2; import static org.apache.datasketches.hll.HllUtil.EMPTY; import static org.apache.datasketches.hll.PreambleUtil.HLL_BYTE_ARR_START; import static org.apache.datasketches.hll.PreambleUtil.extractTgtHllType; import static org.apache.datasketches.hll.TgtHllType.HLL_8; import org.apache.datasketches.SketchesArgumentException; import org.apache.datasketches.memory.Memory; import org.apache.datasketches.memory.WritableMemory; /** * This performs union operations for all HllSketches. This union operator can be configured to be * on or off heap. The source sketch given to this union using the {@link #update(HllSketch)} can * be configured with any precision value <i>lgConfigK</i> (from 4 to 21), any <i>TgtHllType</i> * (HLL_4, HLL_6, HLL_8), and either on or off-heap; and it can be in either of the sparse modes * (<i>LIST</i> or <i>SET</i>), or the dense mode (<i>HLL</i>). * * <p>Although the API for this union operator parallels many of the methods of the * <i>HllSketch</i>, the behavior of the union operator has some fundamental differences.</p> * * <p>First, this union operator is configured with a <i>lgMaxK</i> instead of the normal * <i>lgConfigK</i>. Generally, this union operator will inherit the lowest <i>lgConfigK</i> * less than <i>lgMaxK</i> that it has seen. However, the <i>lgConfigK</i> of incoming sketches that * are still in sparse are ignored. The <i>lgMaxK</i> provides the user the ability to specify the * largest maximum size for the union operation. * * <p>Second, the user cannot specify the {@link TgtHllType} as an input parameter to the union. * Instead, it is specified for the sketch returned with {@link #getResult(TgtHllType)}. * * @author Lee Rhodes * @author Kevin Lang */ public class Union extends BaseHllSketch { final int lgMaxK; private final HllSketch gadget; /** * Construct this Union operator with the default maximum log-base-2 of <i>K</i>. */ public Union() { lgMaxK = HllSketch.DEFAULT_LG_K; gadget = new HllSketch(lgMaxK, HLL_8); } /** * Construct this Union operator with a given maximum log-base-2 of <i>K</i>. * @param lgMaxK the desired maximum log-base-2 of <i>K</i>. This value must be * between 4 and 21 inclusively. */ public Union(final int lgMaxK) { this.lgMaxK = HllUtil.checkLgK(lgMaxK); gadget = new HllSketch(lgMaxK, HLL_8); } /** * Construct this Union operator with a given maximum log-base-2 of <i>K</i> and the given * WritableMemory as the destination for this Union. This WritableMemory is usually configured * for off-heap memory. What remains on the java heap is a thin wrapper object that reads and * writes to the given WritableMemory. * * <p>The given <i>dstMem</i> is checked for the required capacity as determined by * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}. * @param lgMaxK the desired maximum log-base-2 of <i>K</i>. This value must be * between 4 and 21 inclusively. * @param dstWmem the destination writable memory for the sketch. */ public Union(final int lgMaxK, final WritableMemory dstWmem) { this.lgMaxK = HllUtil.checkLgK(lgMaxK); gadget = new HllSketch(lgMaxK, HLL_8, dstWmem); } //used only by writableWrap private Union(final HllSketch sketch) { lgMaxK = sketch.getLgConfigK(); gadget = sketch; } /** * Construct a union operator populated with the given byte array image of an HllSketch. * @param byteArray the given byte array * @return a union operator populated with the given byte array image of an HllSketch. */ public static final Union heapify(final byte[] byteArray) { return heapify(Memory.wrap(byteArray)); } /** * Construct a union operator populated with the given Memory image of an HllSketch. * @param mem the given Memory * @return a union operator populated with the given Memory image of an HllSketch. */ public static final Union heapify(final Memory mem) { final int lgK = HllUtil.checkLgK(mem.getByte(PreambleUtil.LG_K_BYTE)); final HllSketch sk = HllSketch.heapify(mem, false); //allows non-finalized image final Union union = new Union(lgK); union.update(sk); return union; } /** * Wraps the given WritableMemory, which must be a image of a valid updatable HLL_8 sketch, * and may have data. What remains on the java heap is a * thin wrapper object that reads and writes to the given WritableMemory, which, depending on * how the user configures the WritableMemory, may actually reside on the Java heap or off-heap. * * <p>The given <i>dstMem</i> is checked for the required capacity as determined by * {@link HllSketch#getMaxUpdatableSerializationBytes(int, TgtHllType)}, and for the correct type. * @param srcWmem an writable image of a valid sketch with data. * @return a Union operator where the sketch data is in the given dstMem. */ public static final Union writableWrap(final WritableMemory srcWmem) { final TgtHllType tgtHllType = extractTgtHllType(srcWmem); if (tgtHllType != TgtHllType.HLL_8) { throw new SketchesArgumentException( "Union can only wrap writable HLL_8 sketches that were the Gadget of a Union."); } //allows writableWrap of non-finalized image return new Union(HllSketch.writableWrap(srcWmem, false)); } @Override public double getCompositeEstimate() { checkRebuildCurMinNumKxQ(gadget); return gadget.hllSketchImpl.getCompositeEstimate(); } @Override CurMode getCurMode() { return gadget.getCurMode(); } @Override public int getCompactSerializationBytes() { return gadget.getCompactSerializationBytes(); } @Override public double getEstimate() { checkRebuildCurMinNumKxQ(gadget); return gadget.getEstimate(); } /** * Gets the effective <i>lgConfigK</i> for the union operator, which may be less than * <i>lgMaxK</i>. * @return the <i>lgConfigK</i>. */ @Override public int getLgConfigK() { return gadget.getLgConfigK(); } @Override public double getLowerBound(final int numStdDev) { checkRebuildCurMinNumKxQ(gadget); return gadget.getLowerBound(numStdDev); } /** * Returns the maximum size in bytes that this union operator can grow to given a lgK. * * @param lgK The maximum Log2 of K for this union operator. This value must be * between 4 and 21 inclusively. * @return the maximum size in bytes that this union operator can grow to. */ public static int getMaxSerializationBytes(final int lgK) { return HllSketch.getMaxUpdatableSerializationBytes(lgK, TgtHllType.HLL_8); } /** * Return the result of this union operator as an HLL_4 sketch. * @return the result of this union operator as an HLL_4 sketch. */ public HllSketch getResult() { return getResult(HllSketch.DEFAULT_HLL_TYPE); } /** * Return the result of this union operator with the specified {@link TgtHllType} * @param tgtHllType the TgtHllType enum * @return the result of this union operator with the specified TgtHllType */ public HllSketch getResult(final TgtHllType tgtHllType) { checkRebuildCurMinNumKxQ(gadget); return gadget.copyAs(tgtHllType); } @Override public TgtHllType getTgtHllType() { return TgtHllType.HLL_8; } @Override public int getUpdatableSerializationBytes() { return gadget.getUpdatableSerializationBytes(); } @Override public double getUpperBound(final int numStdDev) { checkRebuildCurMinNumKxQ(gadget); return gadget.getUpperBound(numStdDev); } @Override public boolean isCompact() { return gadget.isCompact(); } @Override public boolean isEmpty() { return gadget.isEmpty(); } @Override public boolean isMemory() { return gadget.isMemory(); } @Override public boolean isOffHeap() { return gadget.isOffHeap(); } @Override boolean isOutOfOrder() { return gadget.isOutOfOrder(); } @Override public boolean isSameResource(final Memory mem) { return gadget.isSameResource(mem); } boolean isRebuildCurMinNumKxQFlag() { return gadget.hllSketchImpl.isRebuildCurMinNumKxQFlag(); } void putRebuildCurMinNumKxQFlag(final boolean rebuild) { gadget.hllSketchImpl.putRebuildCurMinNumKxQFlag(rebuild); } /** * Resets to empty and retains the current lgK, but does not change the configured value of * lgMaxK. */ @Override public void reset() { gadget.reset(); } /** * Gets the serialization of this union operator as a byte array in compact form, which is * designed to be heapified only. It is not directly updatable. * For the Union operator, this is the serialization of the internal state of * the union operator as a sketch. * @return the serialization of this union operator as a byte array. */ @Override public byte[] toCompactByteArray() { checkRebuildCurMinNumKxQ(gadget); return gadget.toCompactByteArray(); } @Override public byte[] toUpdatableByteArray() { checkRebuildCurMinNumKxQ(gadget); return gadget.toUpdatableByteArray(); } @Override public String toString(final boolean summary, final boolean hllDetail, final boolean auxDetail, final boolean all) { checkRebuildCurMinNumKxQ(gadget); return gadget.toString(summary, hllDetail, auxDetail, all); } /** * Update this union operator with the given sketch. * @param sketch the given sketch. */ public void update(final HllSketch sketch) { gadget.hllSketchImpl = unionImpl(sketch, gadget, lgMaxK); } @Override void couponUpdate(final int coupon) { if (coupon == EMPTY) { return; } gadget.hllSketchImpl = gadget.hllSketchImpl.couponUpdate(coupon); } // Union operator logic /** * Union the given source and destination sketches. This static method examines the state of * the current internal gadget and the incoming sketch and determines the optimum way to * perform the union. This may involve swapping the merge order, downsampling, transforming, * and / or copying one of the arguments and may completely replace the internals of the union. * * <p>If the union gadget is empty, the source sketch is effectively copied to the union gadget * after any required transformations. * * <p>The direction of the merge is reversed if the union gadget is in LIST or SET mode, and the * source sketch is in HLL mode. This is done to maintain maximum accuracy of the union process. * * <p>The source sketch is downsampled if the source LgK is larger than maxLgK and in HLL mode. * * <p>The union gadget is downsampled if both source and union gadget are in HLL mode * and the source LgK <b>less than</b> the union gadget LgK. * * @param source the given incoming sketch, which cannot be modified. * @param gadget the given gadget sketch, which has a target of HLL_8 and holds the result. * @param lgMaxK the maximum value of log2 K for this union. * @return the union of the two sketches in the form of the internal HllSketchImpl, which is * always in HLL_8 form. */ private static HllSketchImpl unionImpl(final HllSketch source, final HllSketch gadget, final int lgMaxK) { assert gadget.getTgtHllType() == HLL_8; if ((source == null) || source.isEmpty()) { return gadget.hllSketchImpl; } final CurMode srcMode = source.getCurMode(); if (srcMode == CurMode.LIST ) { source.mergeTo(gadget); return gadget.hllSketchImpl; } final int srcLgK = source.getLgConfigK(); final int gadgetLgK = gadget.getLgConfigK(); final boolean srcIsMem = source.isMemory(); final boolean gdtIsMem = gadget.isMemory(); final boolean gdtEmpty = gadget.isEmpty(); if (srcMode == CurMode.SET ) { if (gdtEmpty && (srcLgK == gadgetLgK) && (!srcIsMem) && (!gdtIsMem)) { gadget.hllSketchImpl = source.copyAs(HLL_8).hllSketchImpl; return gadget.hllSketchImpl; } source.mergeTo(gadget); return gadget.hllSketchImpl; } //Hereafter, the source is in HLL mode. final int bit0 = gdtIsMem ? 1 : 0; final int bits1_2 = (gdtEmpty ? 3 : gadget.getCurMode().ordinal()) << 1; final int bit3 = (srcLgK < gadgetLgK) ? 8 : 0; final int bit4 = (srcLgK > lgMaxK) ? 16 : 0; final int sw = bit4 | bit3 | bits1_2 | bit0; HllSketchImpl hllSketchImpl = null; //never returned as null switch (sw) { case 0: //src <= max, src >= gdt, gdtLIST, gdtHeap case 8: //src <= max, src < gdt, gdtLIST, gdtHeap case 2: //src <= max, src >= gdt, gdtSET, gdtHeap case 10://src <= max, src < gdt, gdtSET, gdtHeap { //Action: copy src, reverse merge w/autofold, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 16://src > max, src >= gdt, gdtList, gdtHeap case 18://src > max, src >= gdt, gdtSet, gdtHeap { //Action: downsample src to MaxLgK, reverse merge w/autofold, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,heap,list/set) -> src(Hll8,heap,hll) hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 1: //src <= max, src >= gdt, gdtLIST, gdtMemory case 9: //src <= max, src < gdt, gdtLIST, gdtMemory case 3: //src <= max, src >= gdt, gdtSET, gdtMemory case 11://src <= max, src < gdt, gdtSET, gdtMemory { //Action: copy src, reverse merge w/autofold, use gdt memory, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,mem,list/set) -> src(Hll8,heap,hll) hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 17://src > max, src >= gdt, gdtList, gdtMemory case 19://src > max, src >= gdt, gdtSet, gdtMemory { //Action: downsample src to MaxLgK, reverse merge w/autofold, use gdt memory, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); gadget.mergeTo(srcHll8Heap); //merge gdt(Hll8,mem,list/set) -> src(Hll8,heap,hll), autofold hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 4: //src <= max, src >= gdt, gdtHLL, gdtHeap case 20://src > max, src >= gdt, gdtHLL, gdtHeap case 5: //src <= max, src >= gdt, gdtHLL, gdtMemory case 21://src > max, src >= gdt, gdtHLL, gdtMemory { //Action: forward HLL merge w/autofold, ooof=True //merge src(Hll4,6,8,heap/mem,Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) mergeHlltoHLLmode(source, gadget, srcLgK, gadgetLgK, srcIsMem, gdtIsMem); hllSketchImpl = gadget.putOutOfOrderFlag(true).hllSketchImpl; break; } case 12://src <= max, src < gdt, gdtHLL, gdtHeap { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, ooof=True final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); //merge src(Hll4,6,8;heap/mem,Mode=HLL) -> gdt(Hll8,heap,hll) mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcIsMem, false); hllSketchImpl = gdtHll8Heap.putOutOfOrderFlag(true).hllSketchImpl; break; } case 13://src <= max, src < gdt, gdtHLL, gdtMemory { //Action: downsample gdt to srcLgK, forward HLL merge w/autofold, use gdt memory, ooof=True final HllSketch gdtHll8Heap = downsample(gadget, srcLgK); //merge src(Hll4,6,8;heap/mem;Mode=HLL) -> gdt(Hll8,heap,Mode=HLL) mergeHlltoHLLmode(source, gdtHll8Heap, srcLgK, gadgetLgK, srcIsMem, false); hllSketchImpl = useGadgetMemory(gadget, gdtHll8Heap, true).hllSketchImpl; break; } case 6: //src <= max, src >= gdt, gdtEmpty, gdtHeap case 14://src <= max, src < gdt, gdtEmpty, gdtHeap { //Action: copy src, replace gdt, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 22://src > max, src >= gdt, gdtEmpty, gdtHeap { //Action: downsample src to lgMaxK, replace gdt, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); hllSketchImpl = srcHll8Heap.hllSketchImpl; break; } case 7: //src <= max, src >= gdt, gdtEmpty, gdtMemory case 15://src <= max, src < gdt, gdtEmpty, gdtMemory { //Action: copy src, use gdt memory, ooof=src final HllSketch srcHll8Heap = source.copyAs(HLL_8); hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } case 23://src > max, src >= gdt, gdtEmpty, gdtMemory, replace mem, downsample src, ooof=src { //Action: downsample src to lgMaxK, use gdt memory, ooof=src final HllSketch srcHll8Heap = downsample(source, lgMaxK); hllSketchImpl = useGadgetMemory(gadget, srcHll8Heap, false).hllSketchImpl; break; } //default: return gadget.hllSketchImpl; //not possible } return hllSketchImpl; } private static final HllSketch useGadgetMemory( final HllSketch gadget, final HllSketch hll8Heap, final boolean setOooFlag) { final WritableMemory wmem = gadget.getWritableMemory(); //use the gdt wmem final byte[] byteArr = hll8Heap.toUpdatableByteArray(); //serialize srcCopy wmem.putByteArray(0, byteArr, 0, byteArr.length); //replace old data with new return (setOooFlag) ? HllSketch.writableWrap(wmem).putOutOfOrderFlag(true) //wrap, set oooflag, return : HllSketch.writableWrap(wmem); //wrap & return } private static final void mergeHlltoHLLmode(final HllSketch src, final HllSketch tgt, final int srcLgK, final int tgtLgK, final boolean srcIsMem, final boolean tgtIsMem) { final int sw = (tgtIsMem ? 1 : 0) | (srcIsMem ? 2 : 0) | ((srcLgK > tgtLgK) ? 4 : 0) | ((src.getTgtHllType() != HLL_8) ? 8 : 0); switch (sw) { case 0: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=heap final int srcK = 1 << srcLgK; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final byte tgtV = tgtArr[i]; tgtArr[i] = (srcV > tgtV) ? srcV : tgtV; } break; } case 1: { //HLL_8, srcLgK=tgtLgK, src=heap, tgt=mem final int srcK = 1 << srcLgK; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + i); tgtMem.putByte(HLL_BYTE_ARR_START + i, (srcV > tgtV) ? srcV : tgtV); } break; } case 2: { //HLL_8, srcLgK=tgtLgK, src=mem, tgt=heap final int srcK = 1 << srcLgK; final Memory srcMem = src.getMemory(); final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final byte tgtV = tgtArr[i]; tgtArr[i] = (srcV > tgtV) ? srcV : tgtV; } break; } case 3: { //HLL_8, srcLgK=tgtLgK, src=mem, tgt=mem final int srcK = 1 << srcLgK; final Memory srcMem = src.getMemory(); final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + i); tgtMem.putByte(HLL_BYTE_ARR_START + i, (srcV > tgtV) ? srcV : tgtV); } break; } case 4: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=heap final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final int j = i & tgtKmask; final byte tgtV = tgtArr[j]; tgtArr[j] = (srcV > tgtV) ? srcV : tgtV; } break; } case 5: { //HLL_8, srcLgK>tgtLgK, src=heap, tgt=mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final byte[] srcArr = ((Hll8Array) src.hllSketchImpl).hllByteArr; final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcArr[i]; final int j = i & tgtKmask; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + j); tgtMem.putByte(HLL_BYTE_ARR_START + j, (srcV > tgtV) ? srcV : tgtV); } break; } case 6: { //HLL_8, srcLgK>tgtLgK, src=mem, tgt=heap final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final Memory srcMem = src.getMemory(); final byte[] tgtArr = ((Hll8Array) tgt.hllSketchImpl).hllByteArr; for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final int j = i & tgtKmask; final byte tgtV = tgtArr[j]; tgtArr[j] = (srcV > tgtV) ? srcV : tgtV; } break; } case 7: { //HLL_8, srcLgK>tgtLgK, src=mem, tgt=mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final Memory srcMem = src.getMemory(); final WritableMemory tgtMem = tgt.getWritableMemory(); for (int i = 0; i < srcK; i++) { final byte srcV = srcMem.getByte(HLL_BYTE_ARR_START + i); final int j = i & tgtKmask; final byte tgtV = tgtMem.getByte(HLL_BYTE_ARR_START + j); tgtMem.putByte(HLL_BYTE_ARR_START + j, (srcV > tgtV) ? srcV : tgtV); } break; } case 8: case 9: case 10: case 11: { //!HLL_8, srcLgK=tgtLgK, src=heap/mem, tgt=heap/mem final int srcK = 1 << srcLgK; final AbstractHllArray srcAbsHllArr = (AbstractHllArray)(src.hllSketchImpl); final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); for (int i = 0; i < srcK; i++) { final int srcV = srcAbsHllArr.getSlotValue(i); tgtAbsHllArr.updateSlotNoKxQ(i, srcV); } break; } case 12: case 13: case 14: case 15: { //!HLL_8, srcLgK>tgtLgK, src=heap/mem, tgt=heap/mem final int srcK = 1 << srcLgK; final int tgtKmask = (1 << tgtLgK) - 1; final AbstractHllArray srcAbsHllArr = (AbstractHllArray)(src.hllSketchImpl); final AbstractHllArray tgtAbsHllArr = (AbstractHllArray)(tgt.hllSketchImpl); for (int i = 0; i < srcK; i++) { final int srcV = srcAbsHllArr.getSlotValue(i); final int j = i & tgtKmask; tgtAbsHllArr.updateSlotNoKxQ(j, srcV); } break; } } tgt.hllSketchImpl.putRebuildCurMinNumKxQFlag(true); } //Used by union operator. Always copies or downsamples to Heap HLL_8. //Caller must ultimately manage oooFlag, as caller has more context. /** * Copies or downsamples the given candidate HLLmode sketch to tgtLgK, HLL_8, on the heap. * * @param candidate the HllSketch to downsample, must be in HLL mode. * @param tgtLgK the LgK to downsample to. * @return the downsampled HllSketch. */ private static final HllSketch downsample(final HllSketch candidate, final int tgtLgK) { final AbstractHllArray candArr = (AbstractHllArray) candidate.hllSketchImpl; final HllArray tgtHllArr = HllArray.newHeapHll(tgtLgK, TgtHllType.HLL_8); final PairIterator candItr = candArr.iterator(); while (candItr.nextValid()) { tgtHllArr.couponUpdate(candItr.getPair()); //rebuilds KxQ, etc. } //both of these are required for isomorphism tgtHllArr.putHipAccum(candArr.getHipAccum()); tgtHllArr.putOutOfOrder(candidate.isOutOfOrder()); tgtHllArr.putRebuildCurMinNumKxQFlag(false); return new HllSketch(tgtHllArr); } //Used to rebuild curMin, numAtCurMin and KxQ registers, due to high performance merge operation static final void checkRebuildCurMinNumKxQ(final HllSketch sketch) { final HllSketchImpl hllSketchImpl = sketch.hllSketchImpl; final CurMode curMode = sketch.getCurMode(); final TgtHllType tgtHllType = sketch.getTgtHllType(); final boolean rebuild = hllSketchImpl.isRebuildCurMinNumKxQFlag(); if ( !rebuild || (curMode != CurMode.HLL) || (tgtHllType != HLL_8) ) { return; } final AbstractHllArray absHllArr = (AbstractHllArray)(hllSketchImpl); int curMin = 64; int numAtCurMin = 0; double kxq0 = 1 << absHllArr.getLgConfigK(); double kxq1 = 0; final PairIterator itr = absHllArr.iterator(); while (itr.nextAll()) { final int v = itr.getValue(); if (v > 0) { if (v < 32) { kxq0 += invPow2(v) - 1.0; } else { kxq1 += invPow2(v) - 1.0; } } if (v > curMin) { continue; } if (v < curMin) { curMin = v; numAtCurMin = 1; } else { numAtCurMin++; } } absHllArr.putKxQ0(kxq0); absHllArr.putKxQ1(kxq1); absHllArr.putCurMin(curMin); absHllArr.putNumAtCurMin(numAtCurMin); absHllArr.putRebuildCurMinNumKxQFlag(false); //HipAccum is not affected } }
Covered another use-case.
src/main/java/org/apache/datasketches/hll/Union.java
Covered another use-case.
<ide><path>rc/main/java/org/apache/datasketches/hll/Union.java <ide> final byte[] byteArr = hll8Heap.toUpdatableByteArray(); //serialize srcCopy <ide> wmem.putByteArray(0, byteArr, 0, byteArr.length); //replace old data with new <ide> return (setOooFlag) <del> ? HllSketch.writableWrap(wmem).putOutOfOrderFlag(true) //wrap, set oooflag, return <del> : HllSketch.writableWrap(wmem); //wrap & return <add> ? HllSketch.writableWrap(wmem, false).putOutOfOrderFlag(true) //wrap, set oooflag, return <add> : HllSketch.writableWrap(wmem, false); //wrap & return <ide> } <ide> <ide> private static final void mergeHlltoHLLmode(final HllSketch src, final HllSketch tgt,
JavaScript
agpl-3.0
8a14a2919514d16973180baf2a7517ba304a3368
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
function CDrawingDocument() { this.Native = window.native; this.Api = window.editor; this.IsLockObjectsEnable = false; this.LogicDocument = null; this.CanvasHitContext = CreateHitControl(); this.m_dTargetSize = 0; this.m_lCurrentPage = -1; this.Frame = null; this.Table = null; this.AutoShapesTrack = new CAutoshapeTrack(); this.m_oWordControl = this; this.IsUpdateOverlayOnlyEnd = false; this.IsUpdateOverlayOnlyEndReturn = false; this.IsUpdateOverlayOnEndCheck = false; this.m_bIsSelection = false; this.m_bIsMouseLock = false; this.IsKeyDownButNoPress = false; this.bIsUseKeyPress = false; this.m_sLockedCursorType = ""; this.AutoShapesTrackLockPageNum = -1; // inline text track this.InlineTextTrackEnabled = false; this.InlineTextTrack = null; this.InlineTextTrackPage = -1; } CDrawingDocument.prototype = { AfterLoad : function() { this.m_oWordControl = this; this.LogicDocument = window.editor.WordControl.m_oLogicDocument; this.LogicDocument.DrawingDocument = this; }, RenderPage : function(nPageIndex) { var _graphics = new CDrawingStream(); this.LogicDocument.DrawPage(nPageIndex, _graphics); }, // init lock objects draw Start_CollaborationEditing : function() { this.IsLockObjectsEnable = true; this.Native["DD_Start_CollaborationEditing"](); }, // cursor types SetCursorType : function(sType, Data) { if ("" == this.m_sLockedCursorType) this.Native["DD_SetCursorType"](sType, Data); else this.Native["DD_SetCursorType"](this.m_sLockedCursorType, Data); }, LockCursorType : function(sType) { this.m_sLockedCursorType = sType; this.Native["DD_LockCursorType"](sType); }, LockCursorTypeCur : function() { this.m_sLockedCursorType = this.Native["DD_get_LockCursorType"](); }, UnlockCursorType : function() { this.m_sLockedCursorType = ""; this.Native["DD_UnlockCursorType"](); }, // calculatePages OnStartRecalculate : function(pageCount) { this.Native["DD_OnStartRecalculate"](pageCount); }, OnRecalculatePage : function(index, pageObject) { this.Native["DD_OnRecalculatePage"](index, pageObject.Width, pageObject.Height, pageObject.Margins.Left, pageObject.Margins.Top, pageObject.Margins.Right, pageObject.Margins.Bottom); }, OnEndRecalculate : function(isFull, isBreak) { this.Native["DD_OnEndRecalculate"](isFull, isBreak); }, // repaint pages OnRepaintPage : function(index) { this.Native["DD_OnRepaintPage"](index); }, ChangePageAttack : function(pageIndex) { // unused function }, ClearCachePages : function() { this.Native["DD_ClearCachePages"](); }, // is freeze IsFreezePage : function(pageIndex) { return this.Native["DD_IsFreezePage"](pageIndex); }, RenderPageToMemory : function(pageIndex) { var _stream = new CDrawingStream(); _stream.Native = this.Native["DD_GetPageStream"](); this.LogicDocument.DrawPage(pageIndex, _stream); return _stream.Native; }, CheckRasterImageOnScreen : function(src, pageIndex) { if (!this.LogicDocument || !this.LogicDocument.DrawingObjects) return false; var _imgs = this.LogicDocument.DrawingObject.getAllRasterImagesOnPage(i); var _len = _imgs.length; for (var j = 0; j < _len; j++) { if (_imgs[j] == src) return true; } return false; }, FirePaint : function() { this.Native["DD_FirePaint"](); }, IsCursorInTableCur : function(x, y, page) { return this.Native["DD_IsCursorInTable"](x, y, page); }, // convert coords ConvertCoordsToCursorWR : function(x, y, pageIndex, transform) { var _return = null; if (!transform) _return = this.Native["DD_ConvertCoordsToCursor"](x, y, pageIndex); else _return = this.Native["DD_ConvertCoordsToCursor"](x, y, pageIndex, transform.sx, transform.shy, transform.shx, transform.sy, transform.tx, transform.ty); return { X : _return[0], Y : _return[1], Error: _return[2] }; }, ConvertCoordsToAnotherPage : function(x, y, pageCoord, pageNeed) { var _return = this.Native["DD_ConvertCoordsToAnotherPage"](x, y, pageCoord, pageNeed); return { X : _return[0], Y : _return[1], Error: _return[2] }; }, // target TargetStart : function() { this.Native["DD_TargetStart"](); }, TargetEnd : function() { this.Native["DD_TargetEnd"](); }, SetTargetColor : function(r, g, b) { this.Native["DD_SetTargetColor"](r, g, b); }, UpdateTargetTransform : function(matrix) { if (matrix) this.Native["DD_UpdateTargetTransform"](matrix.sx, matrix.shy, matrix.shx, matrix.sy, matrix.tx, matrix.ty); else this.Native["DD_RemoveTargetTransform"](); }, UpdateTarget : function(x, y, pageIndex) { this.LogicDocument.Set_TargetPos( x, y, pageIndex ); this.Native["DD_UpdateTarget"](x, y, pageIndex); }, SetTargetSize : function(size) { this.m_dTargetSize = size; this.Native["DD_SetTargetSize"](size); }, TargetShow : function() { this.Native["DD_TargetShow"](); }, // track images StartTrackImage : function(obj, x, y, w, h, type, pagenum) { // unused function }, // track tables StartTrackTable : function(obj, transform) { // TODO: }, EndTrackTable : function(pointer, bIsAttack) { // TODO: }, // current page SetCurrentPage : function(PageIndex) { this.m_lCurrentPage = this.Native["DD_SetCurrentPage"](PageIndex); }, // select SelectEnabled : function(bIsEnabled) { this.m_bIsSelection = bIsEnabled; if (false === this.m_bIsSelection) { this.SelectClear(); this.OnUpdateOverlay(); } //this.Native["DD_SelectEnabled"](bIsEnabled); }, SelectClear : function() { this.Native["DD_SelectClear"](); }, AddPageSelection : function(pageIndex, x, y, w, h) { this.Native["DD_AddPageSelection"](pageIndex, x, y, w, h); }, OnSelectEnd : function() { // none }, SelectShow : function() { this.OnUpdateOverlay(); }, // search StartSearch : function() { this.Native["DD_StartSearch"](); }, EndSearch : function(bIsChange) { this.Native["DD_EndSearch"](bIsChange); }, // ruler states Set_RulerState_Table : function(markup, transform) { this.Frame = null; this.Table = markup.Table; var _array_params1 = []; _array_params1.push(markup.Internal.RowIndex); _array_params1.push(markup.Internal.CellIndex); _array_params1.push(markup.Internal.PageNum); _array_params1.push(markup.X); _array_params1.push(markup.CurCol); _array_params1.push(markup.CurRow); if (transform) { _array_params1.push(transform.sx); _array_params1.push(transform.shy); _array_params1.push(transform.shx); _array_params1.push(transform.sy); _array_params1.push(transform.tx); _array_params1.push(transform.ty); } var _array_params_margins = []; for (var i = 0; i < markup.Margins.length; i++) { _array_params_margins.push(markup.Margins[i].Left); _array_params_margins.push(markup.Margins[i].Right); } var _array_params_rows = []; for (var i = 0; i < markup.Rows.length; i++) { _array_params_rows.push(markup.Rows[i].Y); _array_params_rows.push(markup.Rows[i].H); } this.Native["DD_Set_RulerState_Table"](_array_params1, markup.Cols, _array_params_margins, _array_params_rows); }, Set_RulerState_Paragraph : function(margins) { this.Table = null; if (margins && margins.Frame) { this.Native["DD_Set_RulerState_Paragraph"](margins.L, margins.T, margins.R, margins.B, true, margins.PageIndex); this.Frame = margins.Frame; } else if (margins) { this.Frame = null; this.Native["DD_Set_RulerState_Paragraph"](margins.L, margins.T, margins.R, margins.B); } else { this.Frame = null; this.Native["DD_Set_RulerState_Paragraph"](); } }, Set_RulerState_HdrFtr : function(bHeader, Y0, Y1) { this.Frame = null; this.Table = null; this.Native["DD_Set_RulerState_HdrFtr"](bHeader, Y0, Y1); }, Update_ParaInd : function( Ind ) { var FirstLine = 0, Left = 0, Right = 0; if ( "undefined" != typeof(Ind) ) { if("undefined" != typeof(Ind.FirstLine)) { FirstLine = Ind.FirstLine; } if("undefined" != typeof(Ind.Left)) { Left = Ind.Left; } if("undefined" != typeof(Ind.Right)) { Right = Ind.Right; } } this.Native["DD_Update_ParaInd"](FirstLine, Left, Right); }, Update_ParaTab : function(Default_Tab, ParaTabs) { var _arr_pos = []; var _arr_types = []; var __tabs = ParaTabs.Tabs; if (undefined === __tabs) __tabs = ParaTabs; var _len = __tabs.length; for (var i = 0; i < _len; i++) { if (__tabs[i].Value == tab_Left) _arr_types.push(g_tabtype_left); else if (__tabs[i].Value == tab_Center) _arr_types.push(g_tabtype_center); else if (__tabs[i].Value == tab_Right) _arr_types.push(g_tabtype_right); else _arr_types.push(g_tabtype_left); _arr_pos.push(__tabs[i].Pos); } this.Native["DD_Update_ParaTab"](Default_Tab, _arr_pos, _arr_types); }, CorrectRulerPosition : function(pos) { if (global_keyboardEvent.AltKey) return pos; return ((pos / 2.5 + 0.5) >> 0) * 2.5; }, UpdateTableRuler : function(isCols, index, position) { this.Native["DD_UpdateTableRuler"](isCols, index, position); }, // convert pixels GetDotsPerMM : function(value) { return value * this.Native["DD_GetDotsPerMM"](); }, GetMMPerDot : function(value) { return value / this.GetDotsPerMM( 1 ); }, GetVisibleMMHeight : function() { return this.Native["DD_GetVisibleMMHeight"](); }, // вот оооочень важная функция. она выкидывает из кэша неиспользуемые шрифты CheckFontCache : function() { var map_used = this.LogicDocument.Document_CreateFontMap(); for (var i in map_used) { this.Native["DD_CheckFontCacheAdd"](map_used[i].Name, map_used[i].Style, map_used[i].Size); } this.Native["DD_CheckFontCache"](); }, // при загрузке документа - нужно понять какие шрифты используются CheckFontNeeds : function() { }, // треки DrawTrack : function(type, matrix, left, top, width, height, isLine, canRotate) { this.AutoShapesTrack.DrawTrack(type, matrix, left, top, width, height, isLine, canRotate); }, DrawTrackSelectShapes : function(x, y, w, h) { this.AutoShapesTrack.DrawTrackSelectShapes(x, y, w, h); }, DrawAdjustment : function(matrix, x, y) { this.AutoShapesTrack.DrawAdjustment(matrix, x, y); }, LockTrackPageNum : function(nPageNum) { this.AutoShapesTrackLockPageNum = nPageNum; //this.Native["DD_AutoShapesTrackLockPageNum"](nPageNum); }, UnlockTrackPageNum : function() { this.AutoShapesTrackLockPageNum = -1; //this.Native["DD_AutoShapesTrackLockPageNum"](-1); }, IsMobileVersion : function() { return false; }, DrawVerAnchor : function(pageNum, xPos) { this.Native["DD_DrawVerAnchor"](pageNum, xPos); }, DrawHorAnchor : function(pageNum, yPos) { this.Native["DD_DrawHorAnchor"](pageNum, yPos); }, // track text (inline) StartTrackText : function() { this.InlineTextTrackEnabled = true; this.InlineTextTrack = null; this.InlineTextTrackPage = -1; this.Native["DD_StartTrackText"](); }, EndTrackText : function() { this.InlineTextTrackEnabled = false; this.LogicDocument.On_DragTextEnd(this.InlineTextTrack, global_keyboardEvent.CtrlKey); this.InlineTextTrack = null; this.InlineTextTrackPage = -1; this.Native["DD_EndTrackText"](); }, // html page StartUpdateOverlay : function() { this.IsUpdateOverlayOnlyEnd = true; }, EndUpdateOverlay : function() { if (this.IsUpdateOverlayOnlyEndReturn) return; this.IsUpdateOverlayOnlyEnd = false; if (this.IsUpdateOverlayOnEndCheck) this.OnUpdateOverlay(); this.IsUpdateOverlayOnEndCheck = false; }, OnUpdateOverlay : function() { if (this.IsUpdateOverlayOnlyEnd) { this.IsUpdateOverlayOnEndCheck = true; return false; } this.Native["DD_Overlay_UpdateStart"](); this.Native["DD_Overlay_Clear"](); var drawingFirst = this.Native["GetDrawingFirstPage"](); var drawingEnd = this.Native["GetDrawingEndPage"](); if (this.m_bIsSelection) { this.Native["DD_Overlay_StartDrawSelection"](); for (var i = drawingFirst; i <= drawingEnd; i++) { if (!this.IsFreezePage(i)) this.LogicDocument.Selection_Draw_Page(i); } this.Native["DD_Overlay_EndDrawSelection"](); } // проверки - внутри this.Native["DD_Overlay_DrawTableOutline"](); // drawShapes (+ track) if (this.LogicDocument.DrawingObjects) { for (var indP = drawingFirst; indP <= drawingEnd; indP++) { this.AutoShapesTrack.SetPageIndexSimple(indP); this.LogicDocument.DrawingObjects.drawSelect(indP); } this.AutoShapesTrack.SetCurrentPage(-100); if (this.LogicDocument.DrawingObjects.needUpdateOverlay()) { this.AutoShapesTrack.PageIndex = -1; this.LogicDocument.DrawingObjects.drawOnOverlay(this.AutoShapesTrack); this.AutoShapesTrack.CorrectOverlayBounds(); } this.AutoShapesTrack.SetCurrentPage(-101); } this.Native["DD_Overlay_DrawTableTrack"](); this.Native["DD_Overlay_DrawFrameTrack"](); if (this.InlineTextTrackEnabled && null != this.InlineTextTrack) { var m = this.InlineTextTrack.transform; if (!m) { this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](this.InlineTextTrackPage, this.InlineTextTrack.X, this.InlineTextTrack.Y, this.InlineTextTrack.Height); } else { this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](this.InlineTextTrackPage, this.InlineTextTrack.X, this.InlineTextTrack.Y, this.InlineTextTrack.Height, m.sx, m.shy, m.shx, m.sy, m.tx, m.ty); } } this.Native["DD_Overlay_DrawHorVerAnchor"](); this.Native["DD_Overlay_UpdateEnd"](); return true; }, OnMouseDown : function(e) { check_MouseDownEvent(e, true); // у Илюхи есть проблема при вводе с клавы, пока нажата кнопка мыши if ((0 == global_mouseEvent.Button) || (undefined == global_mouseEvent.Button)) this.m_bIsMouseLock = true; this.StartUpdateOverlay(); if ((0 == global_mouseEvent.Button) || (undefined == global_mouseEvent.Button)) { var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) { this.EndUpdateOverlay(); return; } if (this.IsFreezePage(pos.Page)) { this.EndUpdateOverlay(); return; } // теперь проверить трек таблиц var ret = this.Native["checkMouseDown_Drawing"](pos.X, pos.Y, pos.Page); if (ret === true) return; this.Native["DD_NeedScrollToTargetFlag"](true); this.LogicDocument.OnMouseDown(global_mouseEvent, pos.X, pos.Y, pos.Page); this.Native["DD_NeedScrollToTargetFlag"](false); } this.Native["DD_CheckTimerScroll"](true); this.EndUpdateOverlay(); }, OnMouseUp : function(e) { check_MouseUpEvent(e); var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) return; if (this.IsFreezePage(pos.Page)) return; this.UnlockCursorType(); this.StartUpdateOverlay(); // восстанавливаем фокус this.m_bIsMouseLock = false; var is_drawing = this.Native["checkMouseUp_Drawing"](pos.X, pos.Y, pos.Page); if (is_drawing === true) return; this.Native["DD_CheckTimerScroll"](false); this.Native.m_bIsMouseUpSend = true; this.Native["DD_NeedScrollToTargetFlag"](true); this.LogicDocument.OnMouseUp(global_mouseEvent, pos.X, pos.Y, pos.Page); this.Native["DD_NeedScrollToTargetFlag"](false); this.Native.m_bIsMouseUpSend = false; this.LogicDocument.Document_UpdateInterfaceState(); this.LogicDocument.Document_UpdateRulersState(); this.EndUpdateOverlay(); }, OnMouseMove : function(e) { check_MouseMoveEvent(e); var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) return; if (this.IsFreezePage(pos.Page)) return; if (this.m_sLockedCursorType != "") this.SetCursorType("default"); this.StartUpdateOverlay(); var is_drawing = this.Native["checkMouseMove_Drawing"](pos.X, pos.Y, pos.Page); if (is_drawing === true) return; this.LogicDocument.OnMouseMove(global_mouseEvent, pos.X, pos.Y, pos.Page); this.EndUpdateOverlay(); }, OnKeyDown : function(e) { check_KeyboardEvent(e); if (this.IsFreezePage(this.m_lCurrentPage)) return; this.StartUpdateOverlay(); this.IsKeyDownButNoPress = true; this.bIsUseKeyPress = (this.LogicDocument.OnKeyDown(global_keyboardEvent) === true) ? false : true; this.EndUpdateOverlay(); }, OnKeyUp : function(e) { global_keyboardEvent.AltKey = false; global_keyboardEvent.CtrlKey = false; global_keyboardEvent.ShiftKey = false; }, OnKeyPress : function(e) { if (false === this.bIsUseKeyPress) return; if (this.IsFreezePage(this.m_lCurrentPage)) return; check_KeyboardEvent(e); this.StartUpdateOverlay(); var retValue = this.LogicDocument.OnKeyPress(global_keyboardEvent); this.EndUpdateOverlay(); return retValue; }, /////////////////////////////////////////// StartTableStylesCheck : function() { }, EndTableStylesCheck : function() { }, CheckTableStyles : function(tableLook) { }, SendControlColors : function() { }, SendThemeColorScheme : function() { }, DrawImageTextureFillShape : function() { }, DrawGuiCanvasTextProps : function() { } }; function check_KeyboardEvent(e) { global_keyboardEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_keyboardEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_keyboardEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_keyboardEvent.Sender = null; global_keyboardEvent.CharCode = e.CharCode; global_keyboardEvent.KeyCode = e.KeyCode; global_keyboardEvent.Which = null; } function check_MouseDownEvent(e, isClicks) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_down; global_mouseEvent.Button = e.Button; global_mouseEvent.Sender = null; if (isClicks) { global_mouseEvent.ClickCount = e.ClickCount; } else { global_mouseEvent.ClickCount = 1; } global_mouseEvent.IsLocked = true; } function check_MouseMoveEvent(e) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_move; global_mouseEvent.Button = e.Button; } function check_MouseUpEvent(e) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_up; global_mouseEvent.Button = e.Button; global_mouseEvent.Sender = null; global_mouseEvent.IsLocked = false; }
Common/Native/Wrappers/DrawingDocument.js
function CDrawingDocument() { this.Native = window.native; this.Api = window.editor; this.IsLockObjectsEnable = false; this.LogicDocument = null; this.CanvasHitContext = CreateHitControl(); this.m_dTargetSize = 0; this.m_lCurrentPage = -1; this.Frame = null; this.Table = null; this.AutoShapesTrack = new CAutoshapeTrack(); this.m_oWordControl = this; this.IsUpdateOverlayOnlyEnd = false; this.IsUpdateOverlayOnlyEndReturn = false; this.IsUpdateOverlayOnEndCheck = false; this.m_bIsSelection = false; this.m_bIsMouseLock = false; this.IsKeyDownButNoPress = false; this.bIsUseKeyPress = false; this.m_sLockedCursorType = ""; this.AutoShapesTrackLockPageNum = -1; } CDrawingDocument.prototype = { AfterLoad : function() { this.m_oWordControl = this; this.LogicDocument = window.editor.WordControl.m_oLogicDocument; this.LogicDocument.DrawingDocument = this; }, RenderPage : function(nPageIndex) { var _graphics = new CDrawingStream(); this.LogicDocument.DrawPage(nPageIndex, _graphics); }, // init lock objects draw Start_CollaborationEditing : function() { this.IsLockObjectsEnable = true; this.Native["DD_Start_CollaborationEditing"](); }, // cursor types SetCursorType : function(sType, Data) { if ("" == this.m_sLockedCursorType) this.Native["DD_SetCursorType"](sType, Data); else this.Native["DD_SetCursorType"](this.m_sLockedCursorType, Data); }, LockCursorType : function(sType) { this.m_sLockedCursorType = sType; this.Native["DD_LockCursorType"](sType); }, LockCursorTypeCur : function() { this.m_sLockedCursorType = this.Native["DD_get_LockCursorType"](); }, UnlockCursorType : function() { this.m_sLockedCursorType = ""; this.Native["DD_UnlockCursorType"](); }, // calculatePages OnStartRecalculate : function(pageCount) { this.Native["DD_OnStartRecalculate"](pageCount); }, OnRecalculatePage : function(index, pageObject) { this.Native["DD_OnRecalculatePage"](index, pageObject.Width, pageObject.Height, pageObject.Margins.Left, pageObject.Margins.Top, pageObject.Margins.Right, pageObject.Margins.Bottom); }, OnEndRecalculate : function(isFull, isBreak) { this.Native["DD_OnEndRecalculate"](isFull, isBreak); }, // repaint pages OnRepaintPage : function(index) { this.Native["DD_OnRepaintPage"](index); }, ChangePageAttack : function(pageIndex) { // unused function }, ClearCachePages : function() { this.Native["DD_ClearCachePages"](); }, // is freeze IsFreezePage : function(pageIndex) { return this.Native["DD_IsFreezePage"](pageIndex); }, RenderPageToMemory : function(pageIndex) { var _stream = new CDrawingStream(); _stream.Native = this.Native["DD_GetPageStream"](); this.LogicDocument.DrawPage(pageIndex, _stream); return _stream.Native; }, CheckRasterImageOnScreen : function(src, pageIndex) { if (!this.LogicDocument || !this.LogicDocument.DrawingObjects) return false; var _imgs = this.LogicDocument.DrawingObject.getAllRasterImagesOnPage(i); var _len = _imgs.length; for (var j = 0; j < _len; j++) { if (_imgs[j] == src) return true; } return false; }, FirePaint : function() { this.Native["DD_FirePaint"](); }, IsCursorInTableCur : function(x, y, page) { return this.Native["DD_IsCursorInTable"](x, y, page); }, // convert coords ConvertCoordsToCursorWR : function(x, y, pageIndex, transform) { var _return = null; if (!transform) _return = this.Native["DD_ConvertCoordsToCursor"](x, y, pageIndex); else _return = this.Native["DD_ConvertCoordsToCursor"](x, y, pageIndex, transform.sx, transform.shy, transform.shx, transform.sy, transform.tx, transform.ty); return { X : _return[0], Y : _return[1], Error: _return[2] }; }, ConvertCoordsToAnotherPage : function(x, y, pageCoord, pageNeed) { var _return = this.Native["DD_ConvertCoordsToAnotherPage"](x, y, pageCoord, pageNeed); return { X : _return[0], Y : _return[1], Error: _return[2] }; }, // target TargetStart : function() { this.Native["DD_TargetStart"](); }, TargetEnd : function() { this.Native["DD_TargetEnd"](); }, SetTargetColor : function(r, g, b) { this.Native["DD_SetTargetColor"](r, g, b); }, UpdateTargetTransform : function(matrix) { if (matrix) this.Native["DD_UpdateTargetTransform"](matrix.sx, matrix.shy, matrix.shx, matrix.sy, matrix.tx, matrix.ty); else this.Native["DD_RemoveTargetTransform"](); }, UpdateTarget : function(x, y, pageIndex) { this.LogicDocument.Set_TargetPos( x, y, pageIndex ); this.Native["DD_UpdateTarget"](x, y, pageIndex); }, SetTargetSize : function(size) { this.m_dTargetSize = size; this.Native["DD_SetTargetSize"](size); }, TargetShow : function() { this.Native["DD_TargetShow"](); }, // track images StartTrackImage : function(obj, x, y, w, h, type, pagenum) { // unused function }, // track tables StartTrackTable : function(obj, transform) { // TODO: }, EndTrackTable : function(pointer, bIsAttack) { // TODO: }, // current page SetCurrentPage : function(PageIndex) { this.m_lCurrentPage = this.Native["DD_SetCurrentPage"](PageIndex); }, // select SelectEnabled : function(bIsEnabled) { this.m_bIsSelection = bIsEnabled; if (false === this.m_bIsSelection) { this.SelectClear(); this.OnUpdateOverlay(); } //this.Native["DD_SelectEnabled"](bIsEnabled); }, SelectClear : function() { this.Native["DD_SelectClear"](); }, AddPageSelection : function(pageIndex, x, y, w, h) { this.Native["DD_AddPageSelection"](pageIndex, x, y, w, h); }, OnSelectEnd : function() { // none }, SelectShow : function() { this.OnUpdateOverlay(); }, // search StartSearch : function() { this.Native["DD_StartSearch"](); }, EndSearch : function(bIsChange) { this.Native["DD_EndSearch"](bIsChange); }, // ruler states Set_RulerState_Table : function(markup, transform) { this.Frame = null; this.Table = markup.Table; var _array_params1 = []; _array_params1.push(markup.Internal.RowIndex); _array_params1.push(markup.Internal.CellIndex); _array_params1.push(markup.Internal.PageNum); _array_params1.push(markup.X); _array_params1.push(markup.CurCol); _array_params1.push(markup.CurRow); if (transform) { _array_params1.push(transform.sx); _array_params1.push(transform.shy); _array_params1.push(transform.shx); _array_params1.push(transform.sy); _array_params1.push(transform.tx); _array_params1.push(transform.ty); } var _array_params_margins = []; for (var i = 0; i < markup.Margins.length; i++) { _array_params_margins.push(markup.Margins[i].Left); _array_params_margins.push(markup.Margins[i].Right); } var _array_params_rows = []; for (var i = 0; i < markup.Rows.length; i++) { _array_params_rows.push(markup.Rows[i].Y); _array_params_rows.push(markup.Rows[i].H); } this.Native["DD_Set_RulerState_Table"](_array_params1, markup.Cols, _array_params_margins, _array_params_rows); }, Set_RulerState_Paragraph : function(margins) { this.Table = null; if (margins && margins.Frame) { this.Native["DD_Set_RulerState_Paragraph"](margins.L, margins.T, margins.R, margins.B, true, margins.PageIndex); this.Frame = margins.Frame; } else if (margins) { this.Frame = null; this.Native["DD_Set_RulerState_Paragraph"](margins.L, margins.T, margins.R, margins.B); } else { this.Frame = null; this.Native["DD_Set_RulerState_Paragraph"](); } }, Set_RulerState_HdrFtr : function(bHeader, Y0, Y1) { this.Frame = null; this.Table = null; this.Native["DD_Set_RulerState_HdrFtr"](bHeader, Y0, Y1); }, Update_ParaInd : function( Ind ) { var FirstLine = 0, Left = 0, Right = 0; if ( "undefined" != typeof(Ind) ) { if("undefined" != typeof(Ind.FirstLine)) { FirstLine = Ind.FirstLine; } if("undefined" != typeof(Ind.Left)) { Left = Ind.Left; } if("undefined" != typeof(Ind.Right)) { Right = Ind.Right; } } this.Native["DD_Update_ParaInd"](FirstLine, Left, Right); }, Update_ParaTab : function(Default_Tab, ParaTabs) { var _arr_pos = []; var _arr_types = []; var __tabs = ParaTabs.Tabs; if (undefined === __tabs) __tabs = ParaTabs; var _len = __tabs.length; for (var i = 0; i < _len; i++) { if (__tabs[i].Value == tab_Left) _arr_types.push(g_tabtype_left); else if (__tabs[i].Value == tab_Center) _arr_types.push(g_tabtype_center); else if (__tabs[i].Value == tab_Right) _arr_types.push(g_tabtype_right); else _arr_types.push(g_tabtype_left); _arr_pos.push(__tabs[i].Pos); } this.Native["DD_Update_ParaTab"](Default_Tab, _arr_pos, _arr_types); }, CorrectRulerPosition : function(pos) { if (global_keyboardEvent.AltKey) return pos; return ((pos / 2.5 + 0.5) >> 0) * 2.5; }, UpdateTableRuler : function(isCols, index, position) { this.Native["DD_UpdateTableRuler"](isCols, index, position); }, // convert pixels GetDotsPerMM : function(value) { return value * this.Native["DD_GetDotsPerMM"](); }, GetMMPerDot : function(value) { return value / this.GetDotsPerMM( 1 ); }, GetVisibleMMHeight : function() { return this.Native["DD_GetVisibleMMHeight"](); }, // вот оооочень важная функция. она выкидывает из кэша неиспользуемые шрифты CheckFontCache : function() { var map_used = this.LogicDocument.Document_CreateFontMap(); for (var i in map_used) { this.Native["DD_CheckFontCacheAdd"](map_used[i].Name, map_used[i].Style, map_used[i].Size); } this.Native["DD_CheckFontCache"](); }, // при загрузке документа - нужно понять какие шрифты используются CheckFontNeeds : function() { }, // треки DrawTrack : function(type, matrix, left, top, width, height, isLine, canRotate) { this.AutoShapesTrack.DrawTrack(type, matrix, left, top, width, height, isLine, canRotate); }, DrawTrackSelectShapes : function(x, y, w, h) { this.AutoShapesTrack.DrawTrackSelectShapes(x, y, w, h); }, DrawAdjustment : function(matrix, x, y) { this.AutoShapesTrack.DrawAdjustment(matrix, x, y); }, LockTrackPageNum : function(nPageNum) { this.AutoShapesTrackLockPageNum = nPageNum; //this.Native["DD_AutoShapesTrackLockPageNum"](nPageNum); }, UnlockTrackPageNum : function() { this.AutoShapesTrackLockPageNum = -1; //this.Native["DD_AutoShapesTrackLockPageNum"](-1); }, IsMobileVersion : function() { return false; }, DrawVerAnchor : function(pageNum, xPos) { this.Native["DD_DrawVerAnchor"](pageNum, xPos); }, DrawHorAnchor : function(pageNum, yPos) { this.Native["DD_DrawHorAnchor"](pageNum, yPos); }, // track text (inline) StartTrackText : function() { this.Native["DD_StartTrackText"](); }, EndTrackText : function() { this.Native["DD_EndTrackText"](); }, // html page StartUpdateOverlay : function() { this.IsUpdateOverlayOnlyEnd = true; }, EndUpdateOverlay : function() { if (this.IsUpdateOverlayOnlyEndReturn) return; this.IsUpdateOverlayOnlyEnd = false; if (this.IsUpdateOverlayOnEndCheck) this.OnUpdateOverlay(); this.IsUpdateOverlayOnEndCheck = false; }, OnUpdateOverlay : function() { if (this.IsUpdateOverlayOnlyEnd) { this.IsUpdateOverlayOnEndCheck = true; return false; } this.Native["DD_Overlay_UpdateStart"](); this.Native["DD_Overlay_Clear"](); var drawingFirst = this.Native["GetDrawingFirstPage"](); var drawingEnd = this.Native["GetDrawingEndPage"](); if (this.m_bIsSelection) { this.Native["DD_Overlay_StartDrawSelection"](); for (var i = drawingFirst; i <= drawingEnd; i++) { if (!this.IsFreezePage(i)) this.LogicDocument.Selection_Draw_Page(i); } this.Native["DD_Overlay_EndDrawSelection"](); } // проверки - внутри this.Native["DD_Overlay_DrawTableOutline"](); // drawShapes (+ track) if (this.LogicDocument.DrawingObjects) { for (var indP = drawingFirst; indP <= drawingEnd; indP++) { this.AutoShapesTrack.SetPageIndexSimple(indP); this.LogicDocument.DrawingObjects.drawSelect(indP); } this.AutoShapesTrack.SetCurrentPage(-100); if (this.LogicDocument.DrawingObjects.needUpdateOverlay()) { this.AutoShapesTrack.PageIndex = -1; this.LogicDocument.DrawingObjects.drawOnOverlay(this.AutoShapesTrack); this.AutoShapesTrack.CorrectOverlayBounds(); } this.AutoShapesTrack.SetCurrentPage(-101); } this.Native["DD_Overlay_DrawTableTrack"](); this.Native["DD_Overlay_DrawFrameTrack"](); this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](); this.Native["DD_Overlay_DrawHorVerAnchor"](); this.Native["DD_Overlay_UpdateEnd"](); return true; }, OnMouseDown : function(e) { check_MouseDownEvent(e, true); // у Илюхи есть проблема при вводе с клавы, пока нажата кнопка мыши if ((0 == global_mouseEvent.Button) || (undefined == global_mouseEvent.Button)) this.m_bIsMouseLock = true; this.StartUpdateOverlay(); if ((0 == global_mouseEvent.Button) || (undefined == global_mouseEvent.Button)) { var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) { this.EndUpdateOverlay(); return; } if (this.IsFreezePage(pos.Page)) { this.EndUpdateOverlay(); return; } // теперь проверить трек таблиц var ret = this.Native["checkMouseDown_Drawing"](pos.X, pos.Y, pos.Page); if (ret === true) return; this.Native["DD_NeedScrollToTargetFlag"](true); this.LogicDocument.OnMouseDown(global_mouseEvent, pos.X, pos.Y, pos.Page); this.Native["DD_NeedScrollToTargetFlag"](false); } this.Native["DD_CheckTimerScroll"](true); this.EndUpdateOverlay(); }, OnMouseUp : function(e) { check_MouseUpEvent(e); var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) return; if (this.IsFreezePage(pos.Page)) return; this.UnlockCursorType(); this.StartUpdateOverlay(); // восстанавливаем фокус this.m_bIsMouseLock = false; var is_drawing = this.Native["checkMouseUp_Drawing"](pos.X, pos.Y, pos.Page); if (is_drawing === true) return; this.Native["DD_CheckTimerScroll"](false); this.Native.m_bIsMouseUpSend = true; this.Native["DD_NeedScrollToTargetFlag"](true); this.LogicDocument.OnMouseUp(global_mouseEvent, pos.X, pos.Y, pos.Page); this.Native["DD_NeedScrollToTargetFlag"](false); this.Native.m_bIsMouseUpSend = false; this.LogicDocument.Document_UpdateInterfaceState(); this.LogicDocument.Document_UpdateRulersState(); this.EndUpdateOverlay(); }, OnMouseMove : function(e) { check_MouseMoveEvent(e); var pos = null; if (this.AutoShapesTrackLockPageNum == -1) pos = this.Native["DD_ConvertCoordsFromCursor"](global_mouseEvent.X, global_mouseEvent.Y); else pos = this.Native["DD_ConvetToPageCoords"](global_mouseEvent.X, global_mouseEvent.Y, this.AutoShapesTrackLockPageNum); if (pos.Page == -1) return; if (this.IsFreezePage(pos.Page)) return; if (this.m_sLockedCursorType != "") this.SetCursorType("default"); this.StartUpdateOverlay(); var is_drawing = this.Native["checkMouseMove_Drawing"](pos.X, pos.Y, pos.Page); if (is_drawing === true) return; this.LogicDocument.OnMouseMove(global_mouseEvent, pos.X, pos.Y, pos.Page); this.EndUpdateOverlay(); }, OnKeyDown : function(e) { check_KeyboardEvent(e); if (this.IsFreezePage(this.m_lCurrentPage)) return; this.StartUpdateOverlay(); this.IsKeyDownButNoPress = true; this.bIsUseKeyPress = (this.LogicDocument.OnKeyDown(global_keyboardEvent) === true) ? false : true; this.EndUpdateOverlay(); }, OnKeyUp : function(e) { global_keyboardEvent.AltKey = false; global_keyboardEvent.CtrlKey = false; global_keyboardEvent.ShiftKey = false; }, OnKeyPress : function(e) { if (false === this.bIsUseKeyPress) return; if (this.IsFreezePage(this.m_lCurrentPage)) return; check_KeyboardEvent(e); this.StartUpdateOverlay(); var retValue = this.LogicDocument.OnKeyPress(global_keyboardEvent); this.EndUpdateOverlay(); return retValue; }, /////////////////////////////////////////// StartTableStylesCheck : function() { }, EndTableStylesCheck : function() { }, CheckTableStyles : function(tableLook) { }, SendControlColors : function() { }, SendThemeColorScheme : function() { }, DrawImageTextureFillShape : function() { }, DrawGuiCanvasTextProps : function() { } }; function check_KeyboardEvent(e) { global_keyboardEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_keyboardEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_keyboardEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_keyboardEvent.Sender = null; global_keyboardEvent.CharCode = e.CharCode; global_keyboardEvent.KeyCode = e.KeyCode; global_keyboardEvent.Which = null; } function check_MouseDownEvent(e, isClicks) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_down; global_mouseEvent.Button = e.Button; global_mouseEvent.Sender = null; if (isClicks) { global_mouseEvent.ClickCount = e.ClickCount; } else { global_mouseEvent.ClickCount = 1; } global_mouseEvent.IsLocked = true; } function check_MouseMoveEvent(e) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_move; global_mouseEvent.Button = e.Button; } function check_MouseUpEvent(e) { global_mouseEvent.X = e.X; global_mouseEvent.Y = e.Y; global_mouseEvent.AltKey = ((e.Flags & 0x01) == 0x01); global_mouseEvent.CtrlKey = ((e.Flags & 0x02) == 0x02); global_mouseEvent.ShiftKey = ((e.Flags & 0x04) == 0x04); global_mouseEvent.Type = g_mouse_event_type_up; global_mouseEvent.Button = e.Button; global_mouseEvent.Sender = null; global_mouseEvent.IsLocked = false; }
git-svn-id: svn://192.168.3.15/activex/AVS/Sources/TeamlabOffice/trunk/OfficeWeb@55137 954022d7-b5bf-4e40-9824-e11837661b57
Common/Native/Wrappers/DrawingDocument.js
<ide><path>ommon/Native/Wrappers/DrawingDocument.js <ide> this.m_sLockedCursorType = ""; <ide> <ide> this.AutoShapesTrackLockPageNum = -1; <add> <add> // inline text track <add> this.InlineTextTrackEnabled = false; <add> this.InlineTextTrack = null; <add> this.InlineTextTrackPage = -1; <ide> } <ide> <ide> CDrawingDocument.prototype = <ide> // track text (inline) <ide> StartTrackText : function() <ide> { <add> this.InlineTextTrackEnabled = true; <add> this.InlineTextTrack = null; <add> this.InlineTextTrackPage = -1; <ide> this.Native["DD_StartTrackText"](); <ide> }, <ide> EndTrackText : function() <ide> { <add> this.InlineTextTrackEnabled = false; <add> <add> this.LogicDocument.On_DragTextEnd(this.InlineTextTrack, global_keyboardEvent.CtrlKey); <add> this.InlineTextTrack = null; <add> this.InlineTextTrackPage = -1; <ide> this.Native["DD_EndTrackText"](); <ide> }, <ide> <ide> <ide> this.Native["DD_Overlay_DrawTableTrack"](); <ide> this.Native["DD_Overlay_DrawFrameTrack"](); <del> this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](); <add> <add> if (this.InlineTextTrackEnabled && null != this.InlineTextTrack) <add> { <add> var m = this.InlineTextTrack.transform; <add> if (!m) <add> { <add> this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](this.InlineTextTrackPage, <add> this.InlineTextTrack.X, this.InlineTextTrack.Y, this.InlineTextTrack.Height); <add> } <add> else <add> { <add> this.Native["DD_Overlay_DrawInlineTextTrackEnabled"](this.InlineTextTrackPage, <add> this.InlineTextTrack.X, this.InlineTextTrack.Y, this.InlineTextTrack.Height, <add> m.sx, m.shy, m.shx, m.sy, m.tx, m.ty); <add> } <add> } <add> <ide> this.Native["DD_Overlay_DrawHorVerAnchor"](); <ide> <ide> this.Native["DD_Overlay_UpdateEnd"]();
Java
apache-2.0
b7ee439ad499fe96b823253fbe351826af0305f8
0
XDean/Java-EX
package xdean.jex.config; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.Properties; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; @Slf4j @UtilityClass public class Config { private final Properties CONFIG = new Properties(); private Path configFile; public void locate(Path configPath, Path defaultConfig) { try { if (Files.notExists(configPath)) { if (Files.exists(defaultConfig)) { Files.copy(defaultConfig, configPath); } else { Files.createFile(configPath); } } CONFIG.load(Files.newBufferedReader(configPath)); } catch (IOException e) { log.error("IOException", e); } log.debug("Load last config: " + CONFIG.toString()); configFile = configPath; } public Optional<String> getProperty(String key) { return Optional.ofNullable(CONFIG.getProperty(key)); } public Optional<String> getProperty(Object key) { return getProperty(key.toString()); } public String getProperty(Object key, String defaultValue) { return getProperty(key.toString(), defaultValue); } public String getProperty(String key, String defaultValue) { return getProperty(key).orElse(defaultValue); } public void setProperty(Object key, String value) { setProperty(key.toString(), value); } public void setProperty(String key, String value) { CONFIG.setProperty(key, value); save(); } public void setIfAbsent(Object key, String value) { setIfAbsent(key.toString(), value); } public void setIfAbsent(String key, String value) { if (getProperty(key).isPresent() == false) { setProperty(key, value); } } private synchronized void save() { if (configFile == null) { return; } try { CONFIG.store(Files.newOutputStream(configFile), ""); } catch (IOException e) { log.error("", e); } } }
src/main/java/xdean/jex/config/Config.java
package xdean.jex.config; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Optional; import java.util.Properties; import lombok.extern.slf4j.Slf4j; @Slf4j public class Config { private static final Properties CONFIG = new Properties(); private static Path configFile; public static void locate(Path configPath, Path defaultConfig) { try { if (Files.notExists(configPath)) { if (Files.exists(defaultConfig)) { Files.copy(defaultConfig, configPath); } else { Files.createFile(configPath); } } CONFIG.load(Files.newBufferedReader(configPath)); } catch (IOException e) { log.error("IOException", e); } log.debug("Load last config: " + CONFIG.toString()); configFile = configPath; } public static Optional<String> getProperty(String key) { return Optional.ofNullable(CONFIG.getProperty(key)); } public static Optional<String> getProperty(Object key) { return getProperty(key.toString()); } public static String getProperty(Object key, String defaultValue) { return getProperty(key.toString(), defaultValue); } public static String getProperty(String key, String defaultValue) { return getProperty(key).orElse(defaultValue); } public static void setProperty(Object key, String value) { setProperty(key.toString(), value); } public static void setProperty(String key, String value) { CONFIG.setProperty(key, value); save(); } public static void setIfAbsent(Object key, String value) { setIfAbsent(key.toString(), value); } public static void setIfAbsent(String key, String value) { if (getProperty(key).isPresent() == false) { setProperty(key, value); } } private static void save() { if (configFile == null) { return; } try { CONFIG.store(Files.newOutputStream(configFile), ""); } catch (IOException e) { e.printStackTrace(); } } }
config
src/main/java/xdean/jex/config/Config.java
config
<ide><path>rc/main/java/xdean/jex/config/Config.java <ide> import java.util.Optional; <ide> import java.util.Properties; <ide> <add>import lombok.experimental.UtilityClass; <ide> import lombok.extern.slf4j.Slf4j; <ide> <ide> @Slf4j <add>@UtilityClass <ide> public class Config { <del> private static final Properties CONFIG = new Properties(); <del> private static Path configFile; <add> private final Properties CONFIG = new Properties(); <add> private Path configFile; <ide> <del> public static void locate(Path configPath, Path defaultConfig) { <add> public void locate(Path configPath, Path defaultConfig) { <ide> try { <ide> if (Files.notExists(configPath)) { <ide> if (Files.exists(defaultConfig)) { <ide> configFile = configPath; <ide> } <ide> <del> public static Optional<String> getProperty(String key) { <add> public Optional<String> getProperty(String key) { <ide> return Optional.ofNullable(CONFIG.getProperty(key)); <ide> } <ide> <del> public static Optional<String> getProperty(Object key) { <add> public Optional<String> getProperty(Object key) { <ide> return getProperty(key.toString()); <ide> } <ide> <del> public static String getProperty(Object key, String defaultValue) { <add> public String getProperty(Object key, String defaultValue) { <ide> return getProperty(key.toString(), defaultValue); <ide> } <ide> <del> public static String getProperty(String key, String defaultValue) { <add> public String getProperty(String key, String defaultValue) { <ide> return getProperty(key).orElse(defaultValue); <ide> } <ide> <del> public static void setProperty(Object key, String value) { <add> public void setProperty(Object key, String value) { <ide> setProperty(key.toString(), value); <ide> } <ide> <del> public static void setProperty(String key, String value) { <add> public void setProperty(String key, String value) { <ide> CONFIG.setProperty(key, value); <ide> save(); <ide> } <ide> <del> public static void setIfAbsent(Object key, String value) { <add> public void setIfAbsent(Object key, String value) { <ide> setIfAbsent(key.toString(), value); <ide> } <ide> <del> public static void setIfAbsent(String key, String value) { <add> public void setIfAbsent(String key, String value) { <ide> if (getProperty(key).isPresent() == false) { <ide> setProperty(key, value); <ide> } <ide> } <ide> <del> private static void save() { <add> private synchronized void save() { <ide> if (configFile == null) { <ide> return; <ide> } <ide> try { <ide> CONFIG.store(Files.newOutputStream(configFile), ""); <ide> } catch (IOException e) { <del> e.printStackTrace(); <add> log.error("", e); <ide> } <ide> } <ide> }
Java
apache-2.0
d97bac8456843d6d8417107d8533ca0a0871d395
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder.solutions; import java.util.Arrays; public class _977 { public static class Solution1 { public int[] sortedSquares(int[] A) { int[] result = new int[A.length]; for (int i = 0; i < A.length; i++) { result[i] = (int) Math.pow(A[i], 2); } Arrays.sort(result); return result; } } }
src/main/java/com/fishercoder/solutions/_977.java
package com.fishercoder.solutions; import java.util.Arrays; /** * 977. Squares of a Sorted Array * * Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. * * Example 1: * Input: [-4,-1,0,3,10] * Output: [0,1,9,16,100] * * Example 2: * Input: [-7,-3,2,3,11] * Output: [4,9,9,49,121] * * * Note: * 1 <= A.length <= 10000 * -10000 <= A[i] <= 10000 * A is sorted in non-decreasing order. */ public class _977 { public static class Solution1 { public int[] sortedSquares(int[] A) { int[] result = new int[A.length]; for (int i = 0; i < A.length; i++) { result[i] = (int) Math.pow(A[i], 2); } Arrays.sort(result); return result; } } }
refactor 977
src/main/java/com/fishercoder/solutions/_977.java
refactor 977
<ide><path>rc/main/java/com/fishercoder/solutions/_977.java <ide> <ide> import java.util.Arrays; <ide> <del>/** <del> * 977. Squares of a Sorted Array <del> * <del> * Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. <del> * <del> * Example 1: <del> * Input: [-4,-1,0,3,10] <del> * Output: [0,1,9,16,100] <del> * <del> * Example 2: <del> * Input: [-7,-3,2,3,11] <del> * Output: [4,9,9,49,121] <del> * <del> * <del> * Note: <del> * 1 <= A.length <= 10000 <del> * -10000 <= A[i] <= 10000 <del> * A is sorted in non-decreasing order. <del> */ <ide> public class _977 { <del> public static class Solution1 { <del> public int[] sortedSquares(int[] A) { <del> int[] result = new int[A.length]; <del> for (int i = 0; i < A.length; i++) { <del> result[i] = (int) Math.pow(A[i], 2); <del> } <del> Arrays.sort(result); <del> return result; <add> public static class Solution1 { <add> public int[] sortedSquares(int[] A) { <add> int[] result = new int[A.length]; <add> for (int i = 0; i < A.length; i++) { <add> result[i] = (int) Math.pow(A[i], 2); <add> } <add> Arrays.sort(result); <add> return result; <add> } <ide> } <del> } <ide> }
Java
bsd-3-clause
18eefb9666e4d76e0f873379c7b283fe7fe3c7ce
0
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
/* * * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.nc2.iosp.mcidas; import edu.wisc.ssec.mcidas.*; import ucar.nc2.iosp.grid.*; import ucar.unidata.io.RandomAccessFile; import ucar.grid.GridIndex; import java.io.IOException; import java.util.*; /** * Read grid(s) from a McIDAS grid file */ public class McIDASGridReader { /** The file */ protected RandomAccessFile rf; /** An error message */ private String errorMessage; /** Grid index */ private GridIndex gridIndex; /** swap flag */ protected boolean needToSwap = false; /** hashMap of GridDefRecords */ private HashMap<String, McGridDefRecord> gdsMap = new HashMap<String, McGridDefRecord>(); /** * Bean ctor */ public McIDASGridReader() {} /** * Create a McIDASGrid Reader from the file * * @param filename filename * * @throws IOException problem reading file */ public McIDASGridReader(String filename) throws IOException { this(new RandomAccessFile(filename, "r", 2048)); } /** * Create a McIDASGrid Reader from the file * * @param raf RandomAccessFile * * @throws IOException problem reading file */ public McIDASGridReader(RandomAccessFile raf) throws IOException { init(raf); } /** * Initialize the file, read in all the metadata (ala DM_OPEN) * * @param raf RandomAccessFile to read. * * @throws IOException problem reading file */ public final void init(RandomAccessFile raf) throws IOException { rf = raf; raf.order(RandomAccessFile.BIG_ENDIAN); boolean ok = init(); if ( !ok) { throw new IOException("Unable to open McIDAS Grid file: " + errorMessage); } } /** * Initialize this reader. Get the Grid specific info * * @return true if successful * * @throws IOException problem reading the data */ protected boolean init() throws IOException { if (rf == null) { logError("File is null"); return false; } gridIndex = new GridIndex(); rf.order(RandomAccessFile.BIG_ENDIAN); int numEntries = Math.abs(readInt(10)); if (numEntries > 10000000) { needToSwap = true; numEntries = Math.abs(McIDASUtil.swbyt4(numEntries)); if (numEntries > 10000000) { return false; } } // System.out.println("need to Swap = " + needToSwap); // System.out.println("number entries="+numEntries); // go back to the beginning rf.seek(0); // read the fileheader String label = rf.readString(32); //System.out.println("label = " + label); int project = readInt(8); //System.out.println("Project = " + project); int date = readInt(9); //System.out.println("date = " + date); int[] entries = new int[numEntries]; for (int i = 0; i < numEntries; i++) { entries[i] = readInt(i + 11); // sanity check that this is indeed a McIDAS Grid file if (entries[i] < -1) { logError("bad grid offset " + i + ": " + entries[i]); return false; } } // Don't swap: rf.order(RandomAccessFile.BIG_ENDIAN); for (int i = 0; i < numEntries; i++) { if (entries[i] == -1) { continue; } int[] header = new int[64]; rf.seek(entries[i] * 4); rf.readInt(header, 0, 64); if (needToSwap) { swapGridHeader(header); } try { McIDASGridRecord gr = new McIDASGridRecord(entries[i], header); //if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { //if (gr.getGridDefRecordId().equals("CONF X:54 Y:47")) { // figure out how to handle Mercator projections // if ( !(gr.getGridDefRecordId().startsWith("MERC"))) { gridIndex.addGridRecord(gr); if (gdsMap.get(gr.getGridDefRecordId()) == null) { McGridDefRecord mcdef = gr.getGridDefRecord(); //System.out.println("new nav " + mcdef.toString()); gdsMap.put(mcdef.toString(), mcdef); gridIndex.addHorizCoordSys(mcdef); } //} } catch (McIDASException me) { logError("problem creating grid dir"); return false; } } // check to see if there are any grids that we can handle if (gridIndex.getGridRecords().isEmpty()) { logError("no grids found"); return false; } return true; } /** * Swap the grid header, avoiding strings * * @param gh grid header to swap */ private void swapGridHeader(int[] gh) { McIDASUtil.flip(gh, 0, 5); McIDASUtil.flip(gh, 7, 7); McIDASUtil.flip(gh, 9, 10); McIDASUtil.flip(gh, 12, 14); McIDASUtil.flip(gh, 32, 51); } /** * Read the grid * * @param gr the grid record * * @return the data */ public float[] readGrid(McIDASGridRecord gr) { float[] data = null; try { int te = (gr.getOffsetToHeader() + 64) * 4; int rows = gr.getRows(); int cols = gr.getColumns(); rf.seek(te); float scale = (float) gr.getParamScale(); data = new float[rows * cols]; rf.order(needToSwap ? rf.LITTLE_ENDIAN : rf.BIG_ENDIAN); int n = 0; // store such that 0,0 is in lower left corner... for (int nc = 0; nc < cols; nc++) { for (int nr = 0; nr < rows; nr++) { int temp = rf.readInt(); // check for missing value data[(rows - nr - 1) * cols + nc] = (temp == McIDASUtil.MCMISSING) ? Float.NaN : ((float) temp) / scale; } } rf.order(rf.BIG_ENDIAN); } catch (Exception esc) { System.out.println(esc); } return data; } /** * to get the grid header corresponding to the last grid read * * @return McIDASGridDirectory of the last grid read */ public GridIndex getGridIndex() { return gridIndex; } /** * Read an integer * @param word word in file (0 based) to read * * @return int read * * @throws IOException problem reading file */ public int readInt(int word) throws IOException { if (rf == null) { throw new IOException("no file to read from"); } rf.seek(word * 4); // set the order if (needToSwap) { rf.order(RandomAccessFile.LITTLE_ENDIAN); // swap } else { rf.order(RandomAccessFile.BIG_ENDIAN); } int idata = rf.readInt(); rf.order(RandomAccessFile.BIG_ENDIAN); return idata; } /** * Log an error * * @param errMsg message to log */ private void logError(String errMsg) { errorMessage = errMsg; } /** * for testing purposes * * @param args file name * * @throws IOException problem reading file */ public static void main(String[] args) throws IOException { String file = "GRID2001"; if (args.length > 0) { file = args[0]; } McIDASGridReader mg = new McIDASGridReader(file); GridIndex gridIndex = mg.getGridIndex(); List grids = gridIndex.getGridRecords(); System.out.println("found " + grids.size() + " grids"); int num = Math.min(grids.size(), 10); for (int i = 0; i < num; i++) { System.out.println(grids.get(i)); } } }
cdm/src/main/java/ucar/nc2/iosp/mcidas/McIDASGridReader.java
/* * * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package ucar.nc2.iosp.mcidas; import edu.wisc.ssec.mcidas.*; import ucar.nc2.iosp.grid.*; import ucar.unidata.io.RandomAccessFile; import ucar.grid.GridIndex; import java.io.IOException; import java.util.*; /** * Read grid(s) from a McIDAS grid file */ public class McIDASGridReader { /** The file */ protected RandomAccessFile rf; /** An error message */ private String errorMessage; /** Grid index */ private GridIndex gridIndex; /** swap flag */ protected boolean needToSwap = false; /** hashMap of GridDefRecords */ private HashMap<String, McGridDefRecord> gdsMap = new HashMap<String, McGridDefRecord>(); /** * Bean ctor */ public McIDASGridReader() {} /** * Create a McIDASGrid Reader from the file * * @param filename filename * * @throws IOException problem reading file */ public McIDASGridReader(String filename) throws IOException { this(new RandomAccessFile(filename, "r", 2048)); } /** * Create a McIDASGrid Reader from the file * * @param raf RandomAccessFile * * @throws IOException problem reading file */ public McIDASGridReader(RandomAccessFile raf) throws IOException { init(raf); } /** * Initialize the file, read in all the metadata (ala DM_OPEN) * * @param raf RandomAccessFile to read. * * @throws IOException problem reading file */ public final void init(RandomAccessFile raf) throws IOException { rf = raf; raf.order(RandomAccessFile.BIG_ENDIAN); boolean ok = init(); if ( !ok) { throw new IOException("Unable to open McIDAS Grid file: " + errorMessage); } } /** * Initialize this reader. Get the Grid specific info * * @return true if successful * * @throws IOException problem reading the data */ protected boolean init() throws IOException { if (rf == null) { logError("File is null"); return false; } gridIndex = new GridIndex(); rf.order(RandomAccessFile.BIG_ENDIAN); int numEntries = Math.abs(readInt(10)); if (numEntries > 10000000) { needToSwap = true; numEntries = Math.abs(McIDASUtil.swbyt4(numEntries)); if (numEntries > 10000000) { return false; } } // System.out.println("need to Swap = " + needToSwap); // System.out.println("number entries="+numEntries); // go back to the beginning rf.seek(0); // read the fileheader String label = rf.readString(32); //System.out.println("label = " + label); int project = readInt(8); //System.out.println("Project = " + project); int date = readInt(9); //System.out.println("date = " + date); int[] entries = new int[numEntries]; for (int i = 0; i < numEntries; i++) { entries[i] = readInt(i + 11); // sanity check that this is indeed a McIDAS Grid file if (entries[i] < -1) { logError("bad grid offset " + i + ": " + entries[i]); return false; } } // Don't swap: rf.order(RandomAccessFile.BIG_ENDIAN); for (int i = 0; i < numEntries; i++) { if (entries[i] == -1) { continue; } int[] header = new int[64]; rf.seek(entries[i] * 4); rf.readInt(header, 0, 64); if (needToSwap) { swapGridHeader(header); } try { McIDASGridRecord gr = new McIDASGridRecord(entries[i], header); if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { //if (gr.getGridDefRecordId().equals("CONF X:54 Y:47")) { // figure out how to handle Mercator projections // if ( !(gr.getGridDefRecordId().startsWith("MERC"))) { gridIndex.addGridRecord(gr); if (gdsMap.get(gr.getGridDefRecordId()) == null) { McGridDefRecord mcdef = gr.getGridDefRecord(); //System.out.println("new nav " + mcdef.toString()); gdsMap.put(mcdef.toString(), mcdef); gridIndex.addHorizCoordSys(mcdef); } } } catch (McIDASException me) { logError("problem creating grid dir"); return false; } } // check to see if there are any grids that we can handle if (gridIndex.getGridRecords().isEmpty()) { logError("no grids found"); return false; } return true; } /** * Swap the grid header, avoiding strings * * @param gh grid header to swap */ private void swapGridHeader(int[] gh) { McIDASUtil.flip(gh, 0, 5); McIDASUtil.flip(gh, 7, 7); McIDASUtil.flip(gh, 9, 10); McIDASUtil.flip(gh, 12, 14); McIDASUtil.flip(gh, 32, 51); } /** * Read the grid * * @param gr the grid record * * @return the data */ public float[] readGrid(McIDASGridRecord gr) { float[] data = null; try { int te = (gr.getOffsetToHeader() + 64) * 4; int rows = gr.getRows(); int cols = gr.getColumns(); rf.seek(te); float scale = (float) gr.getParamScale(); data = new float[rows * cols]; rf.order(needToSwap ? rf.LITTLE_ENDIAN : rf.BIG_ENDIAN); int n = 0; // store such that 0,0 is in lower left corner... for (int nc = 0; nc < cols; nc++) { for (int nr = 0; nr < rows; nr++) { int temp = rf.readInt(); // check for missing value data[(rows - nr - 1) * cols + nc] = (temp == McIDASUtil.MCMISSING) ? Float.NaN : ((float) temp) / scale; } } rf.order(rf.BIG_ENDIAN); } catch (Exception esc) { System.out.println(esc); } return data; } /** * to get the grid header corresponding to the last grid read * * @return McIDASGridDirectory of the last grid read */ public GridIndex getGridIndex() { return gridIndex; } /** * Read an integer * @param word word in file (0 based) to read * * @return int read * * @throws IOException problem reading file */ public int readInt(int word) throws IOException { if (rf == null) { throw new IOException("no file to read from"); } rf.seek(word * 4); // set the order if (needToSwap) { rf.order(RandomAccessFile.LITTLE_ENDIAN); // swap } else { rf.order(RandomAccessFile.BIG_ENDIAN); } int idata = rf.readInt(); rf.order(RandomAccessFile.BIG_ENDIAN); return idata; } /** * Log an error * * @param errMsg message to log */ private void logError(String errMsg) { errorMessage = errMsg; } /** * for testing purposes * * @param args file name * * @throws IOException problem reading file */ public static void main(String[] args) throws IOException { String file = "GRID2001"; if (args.length > 0) { file = args[0]; } McIDASGridReader mg = new McIDASGridReader(file); GridIndex gridIndex = mg.getGridIndex(); List grids = gridIndex.getGridRecords(); System.out.println("found " + grids.size() + " grids"); int num = Math.min(grids.size(), 10); for (int i = 0; i < num; i++) { System.out.println(grids.get(i)); } } }
allow multiple projections
cdm/src/main/java/ucar/nc2/iosp/mcidas/McIDASGridReader.java
allow multiple projections
<ide><path>dm/src/main/java/ucar/nc2/iosp/mcidas/McIDASGridReader.java <ide> <ide> McIDASGridRecord gr = new McIDASGridRecord(entries[i], <ide> header); <del> if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { <add> //if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { <ide> //if (gr.getGridDefRecordId().equals("CONF X:54 Y:47")) { <ide> // figure out how to handle Mercator projections <ide> // if ( !(gr.getGridDefRecordId().startsWith("MERC"))) { <ide> gdsMap.put(mcdef.toString(), mcdef); <ide> gridIndex.addHorizCoordSys(mcdef); <ide> } <del> } <add> //} <ide> } catch (McIDASException me) { <ide> logError("problem creating grid dir"); <ide> return false;
JavaScript
mit
09779a782fc4cb2577c5a7ff4eea43cfb4890891
0
MineSkin/mineskin.org,MineSkin/mineskin.org,MineSkin/mineskin.org
let apiBaseUrl = "https://api.mineskin.org"; const mineskinApp = angular.module("mineskinApp", ["ui.router", "ui.materialize", "ngFileUpload", "ngCookies", "angularModalService", "ngMeta", "ngStorage"]); mineskinApp.directive("ngPreloadSrc", function () { return { restrict: "A", replace: true, link: function (scope, element, attrs) { var $preloader = $("<img style='display:none'>"); $preloader.attr("src", attrs.ngPreloadSrc); $preloader.on("load", function () { element.attr("src", attrs.ngPreloadSrc); $preloader.remove(); }); $preloader.on("error", function () { if (attrs.ngPreloadFallback) { element.attr("src", attrs.ngPreloadFallback); } $preloader.remove(); }); $preloader.appendTo(element); } } }); // Based on https://gist.github.com/Shoen/6350967 mineskinApp.directive('twitter', ["$timeout", function ($timeout) { return { link: function (scope, element, attr) { $timeout(function () { twttr.widgets.createShareButton( attr.url, element[0], function (el) { }, { count: 'none', text: attr.text } ); }); } } } ]); mineskinApp.directive('selectOnClick', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.on('click', function () { this.select(); }); } }; }); // based on https://www.javainuse.com/angular/angular2_adsense mineskinApp.directive('googleAd', ['$timeout', function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { console.log(attrs); return $timeout(function () { element.append("<ins class=\"adsbygoogle\" style=\"display:block\" data-ad-client=\"ca-pub-2604356629473365\" data-ad-slot=\"" + (attrs.googleAd || '7160666614') + "\" data-ad-format=\"auto\" data-full-width-responsive=\"true\"></ins>"); return (adsbygoogle = window.adsbygoogle || []).push({}); }) } } } ]); mineskinApp.directive('scrolly', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { let raw = element[0]; let timeout = false; angular.element($window).bind('scroll', function () { if (timeout) return; if ($window.scrollY + $window.innerHeight >= raw.offsetTop - 200) { timeout = true; scope.$apply(attrs.scrolly); setTimeout(() => { timeout = false; }, 200); } }) } } }]) mineskinApp.directive('scrollWithView', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { let timeout = false; element.css("transition", "margin-top 100ms ease") angular.element($window).bind('scroll', function () { if (timeout) return; timeout = true; element.css("margin-top", $window.scrollY + 20); setTimeout(() => { timeout = false; }, 10); }) } } }]) mineskinApp.config(function ($stateProvider, $locationProvider, ngMetaProvider) { // $routeProvider // .when("/", { // templateUrl: "/pages/generate.html", // controller: "generatorController" // }) // .when("/gallery", {redirectTo: "/gallery/1"}) // .when("/gallery/:page?", { // templateUrl: "/pages/gallery.html", // controller: "galleryController" // }) // .when("/stats", { // templateUrl: "/pages/stats.html" // }) // .when("/:id", { // templateUrl: "/pages/view.html", // controller: "viewController" // }); $stateProvider .state("index", { url: "/?generateUrl&generateName&generatePrivate&generateCallback", views: { 'tab1': { templateUrl: "/pages/generate.html", controller: "indexController", } }, data: { meta: { title: "MineSkin - Custom Skin Generator", titleSuffix: "", image: "https://mineskin.org/favicon.png" } } }) .state("bulk", { url: "/bulk", views: { 'tab1': { templateUrl: "/pages/generate_bulk.html", controller: "bulkController", } }, data: { meta: { title: "Generate Bulk | MineSkin", titleSuffix: "", image: "https://mineskin.org/favicon.png" } } }) .state("index.stats", { url: "^/stats", onEnter: ["$state", "$stateParams", "ModalService", function ($state, $stateParams, ModalService) { ModalService.showModal({ templateUrl: "/pages/stats.html", controller: ["$scope", "$http", "$interval", function ($scope, $http, $interval) { $scope.refreshStats = function () { $http({ url: apiBaseUrl + "/get/stats", method: "GET" }).then(function (response) { $scope.stats = response.data; }); } $scope.refreshStats(); $interval(function () { $scope.refreshStats(); }, 10000); }] }).then(function (modal) { modal.element.modal({ ready: function () { console.log("ready"); }, complete: function () { console.log("complete"); $(".modal").remove() $state.go("^"); } }) modal.element.modal("open"); }) }], data: { meta: { title: "Stats", image: "https://mineskin.org/favicon.png" } } }) .state("gallery_legacy", { url: "/gallery/:page?query", redirectTo: "gallery" }) .state("gallery", { url: "/gallery?query", views: { 'tab1': {}, 'tab2': { templateUrl: "/pages/gallery.html", controller: "galleryController" } }, data: { meta: { title: "Gallery", image: "https://mineskin.org/favicon.png" } } }) .state("gallery.view", { url: "^/{id:[0-9a-z]{1,32}}", onEnter: ["$state", "$stateParams", "ModalService", "ngMeta", function ($state, $stateParams, ModalService, ngMeta) { console.info("onEnter"); console.log($stateParams); if (!$stateParams.id) return; ModalService.showModal({ templateUrl: "/pages/view.html", controller: "viewController", inputs: { '$stateParams': $stateParams } }).then(function (modal) { modal.element.modal({ ready: function () { console.log("ready"); }, complete: function () { console.log("complete"); $(".modal").remove() $state.go("^"); } }) modal.element.modal("open"); }) }], onExit: ["$state", function ($state) { console.info("onExit") }] }) .state("account", { url: "/account", views: { 'tab1': { templateUrl: "/pages/account.html", controller: "accountController" } }, data: { meta: { title: "Account", image: "https://mineskin.org/favicon.png" } } }) .state("apikey", { url: "/apikey", views: { 'tab1': { templateUrl: "/pages/apikey.html", controller: "apiKeyController" } }, data: { meta: { title: "API Keys", image: "https://mineskin.org/favicon.png" } } }) $locationProvider.html5Mode(true); ngMetaProvider.useTitleSuffix(true); ngMetaProvider.setDefaultTitleSuffix(" | MineSkin"); ngMetaProvider.setDefaultTitle("MineSkin - Custom Skin Generator"); ngMetaProvider.setDefaultTag("image", "https://mineskin.org/favicon.png"); }); mineskinApp.run(['$transitions', '$rootScope', 'ngMeta', function ($transitions, $rootScope, ngMeta) { // https://github.com/vinaygopinath/ngMeta/issues/36#issuecomment-311581385 -> https://github.com/vinaygopinath/ngMeta/issues/25#issuecomment-268954483 $transitions.onFinish({}, function (trans) { $rootScope.$broadcast('$routeChangeSuccess', trans.to()); }); ngMeta.init() }]) function materializeBaseInit() { $('select').material_select(); // https://stackoverflow.com/a/56725559/6257838 document.querySelectorAll('.select-wrapper').forEach(t => t.addEventListener('click', e => e.stopPropagation())) $('.tooltipped').tooltip(); Materialize.updateTextFields(); } //// https://github.com/MineSkin/mineskin.org/issues/13 by @SpraxDev const uuidView = new DataView(new ArrayBuffer(16)); /** * Takes an UUID and converts it into four int32 * * @param {string} uuid Valid UUID (with or without hyphens) * * @returns {number[]} */ function getInt32ForUUID(uuid) { uuid = uuid.replace(/-/g, ''); // Remove hyphens const result = []; uuidView.setBigUint64(0, BigInt(`0x${ uuid.substring(0, 16) }`)); // most significant bits (hex) uuidView.setBigUint64(8, BigInt(`0x${ uuid.substring(16) }`)); // least significant bits (hex) // read int32 for (let i = 0; i < 4; i++) { result[i] = uuidView.getInt32(i * 4, false); } return result; } /** * Takes an array with four int32 and return a string representation * that can be used for Minecraft 1.16+ commands (nbt) * * @param {number[]} uuidInt32 * * @returns {string} */ function formatInt32UUID(uuidInt32) { return `[I;${ uuidInt32[0] },${ uuidInt32[1] },${ uuidInt32[2] },${ uuidInt32[3] }]`; }
js/base.script.js
let apiBaseUrl = "https://api.mineskin.org"; const mineskinApp = angular.module("mineskinApp", ["ui.router", "ui.materialize", "ngFileUpload", "ngCookies", "angularModalService", "ngMeta", "ngStorage"]); mineskinApp.directive("ngPreloadSrc", function () { return { restrict: "A", replace: true, link: function (scope, element, attrs) { var $preloader = $("<img style='display:none'>"); $preloader.attr("src", attrs.ngPreloadSrc); $preloader.on("load", function () { element.attr("src", attrs.ngPreloadSrc); $preloader.remove(); }); $preloader.on("error", function () { if (attrs.ngPreloadFallback) { element.attr("src", attrs.ngPreloadFallback); } $preloader.remove(); }); $preloader.appendTo(element); } } }); // Based on https://gist.github.com/Shoen/6350967 mineskinApp.directive('twitter', ["$timeout", function ($timeout) { return { link: function (scope, element, attr) { $timeout(function () { twttr.widgets.createShareButton( attr.url, element[0], function (el) { }, { count: 'none', text: attr.text } ); }); } } } ]); mineskinApp.directive('selectOnClick', function () { return { restrict: 'A', link: function (scope, element, attrs) { element.on('click', function () { this.select(); }); } }; }); // based on https://www.javainuse.com/angular/angular2_adsense mineskinApp.directive('googleAd', ['$timeout', function ($timeout) { return { restrict: 'A', link: function (scope, element, attrs) { console.log(attrs); return $timeout(function () { element.append("<ins class=\"adsbygoogle\" style=\"display:block\" data-ad-client=\"ca-pub-2604356629473365\" data-ad-slot=\"" + (attrs.googleAd || '7160666614') + "\" data-ad-format=\"auto\" data-full-width-responsive=\"true\"></ins>"); return (adsbygoogle = window.adsbygoogle || []).push({}); }) } } } ]); mineskinApp.directive('scrolly', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { let raw = element[0]; let timeout = false; angular.element($window).bind('scroll', function () { if (timeout) return; if ($window.scrollY + $window.innerHeight >= raw.offsetTop - 200) { timeout = true; scope.$apply(attrs.scrolly); setTimeout(() => { timeout = false; }, 200); } }) } } }]) mineskinApp.directive('scrollWithView', ['$window', function ($window) { return { restrict: 'A', link: function (scope, element, attrs) { let timeout = false; element.css("transition", "margin-top 100ms ease") angular.element($window).bind('scroll', function () { if (timeout) return; timeout = true; element.css("margin-top", $window.scrollY + 20); setTimeout(() => { timeout = false; }, 10); }) } } }]) mineskinApp.config(function ($stateProvider, $locationProvider, ngMetaProvider) { // $routeProvider // .when("/", { // templateUrl: "/pages/generate.html", // controller: "generatorController" // }) // .when("/gallery", {redirectTo: "/gallery/1"}) // .when("/gallery/:page?", { // templateUrl: "/pages/gallery.html", // controller: "galleryController" // }) // .when("/stats", { // templateUrl: "/pages/stats.html" // }) // .when("/:id", { // templateUrl: "/pages/view.html", // controller: "viewController" // }); $stateProvider .state("index", { url: "/?generateUrl&generateName&generatePrivate&generateCallback", views: { 'tab1': { templateUrl: "/pages/generate.html", controller: "indexController", } }, data: { meta: { title: "MineSkin - Custom Skin Generator", titleSuffix: "", image: "https://mineskin.org/favicon.png" } } }) .state("bulk", { url: "/bulk", views: { 'tab1': { templateUrl: "/pages/generate_bulk.html", controller: "bulkController", } }, data: { meta: { title: "Generate Bulk | MineSkin", titleSuffix: "", image: "https://mineskin.org/favicon.png" } } }) .state("index.stats", { url: "^/stats", onEnter: ["$state", "$stateParams", "ModalService", function ($state, $stateParams, ModalService) { ModalService.showModal({ templateUrl: "/pages/stats.html", controller: ["$scope", "$http", "$interval", function ($scope, $http, $interval) { $scope.refreshStats = function () { $http({ url: apiBaseUrl + "/get/stats", method: "GET" }).then(function (response) { $scope.stats = response.data; }); } $scope.refreshStats(); $interval(function () { $scope.refreshStats(); }, 10000); }] }).then(function (modal) { modal.element.modal({ ready: function () { console.log("ready"); }, complete: function () { console.log("complete"); $(".modal").remove() $state.go("^"); } }) modal.element.modal("open"); }) }], data: { meta: { title: "Stats", image: "https://mineskin.org/favicon.png" } } }) .state("gallery", { url: "/gallery/:page?query", params: { page: {value: "1"} }, views: { 'tab1': {}, 'tab2': { templateUrl: "/pages/gallery.html", controller: "galleryController" } }, data: { meta: { title: "Gallery", image: "https://mineskin.org/favicon.png" } } }) .state("gallery.view", { url: "^/{id:[0-9a-z]{1,32}}", onEnter: ["$state", "$stateParams", "ModalService", "ngMeta", function ($state, $stateParams, ModalService, ngMeta) { console.info("onEnter"); console.log($stateParams); if (!$stateParams.id) return; ModalService.showModal({ templateUrl: "/pages/view.html", controller: "viewController", inputs: { '$stateParams': $stateParams } }).then(function (modal) { modal.element.modal({ ready: function () { console.log("ready"); }, complete: function () { console.log("complete"); $(".modal").remove() $state.go("^"); } }) modal.element.modal("open"); }) }], onExit: ["$state", function ($state) { console.info("onExit") }] }) .state("account", { url: "/account", views: { 'tab1': { templateUrl: "/pages/account.html", controller: "accountController" } }, data: { meta: { title: "Account", image: "https://mineskin.org/favicon.png" } } }) .state("apikey", { url: "/apikey", views: { 'tab1': { templateUrl: "/pages/apikey.html", controller: "apiKeyController" } }, data: { meta: { title: "API Keys", image: "https://mineskin.org/favicon.png" } } }) $locationProvider.html5Mode(true); ngMetaProvider.useTitleSuffix(true); ngMetaProvider.setDefaultTitleSuffix(" | MineSkin"); ngMetaProvider.setDefaultTitle("MineSkin - Custom Skin Generator"); ngMetaProvider.setDefaultTag("image", "https://mineskin.org/favicon.png"); }); mineskinApp.run(['$transitions', '$rootScope', 'ngMeta', function ($transitions, $rootScope, ngMeta) { // https://github.com/vinaygopinath/ngMeta/issues/36#issuecomment-311581385 -> https://github.com/vinaygopinath/ngMeta/issues/25#issuecomment-268954483 $transitions.onFinish({}, function (trans) { $rootScope.$broadcast('$routeChangeSuccess', trans.to()); }); ngMeta.init() }]) function materializeBaseInit() { $('select').material_select(); // https://stackoverflow.com/a/56725559/6257838 document.querySelectorAll('.select-wrapper').forEach(t => t.addEventListener('click', e => e.stopPropagation())) $('.tooltipped').tooltip(); Materialize.updateTextFields(); } //// https://github.com/MineSkin/mineskin.org/issues/13 by @SpraxDev const uuidView = new DataView(new ArrayBuffer(16)); /** * Takes an UUID and converts it into four int32 * * @param {string} uuid Valid UUID (with or without hyphens) * * @returns {number[]} */ function getInt32ForUUID(uuid) { uuid = uuid.replace(/-/g, ''); // Remove hyphens const result = []; uuidView.setBigUint64(0, BigInt(`0x${ uuid.substring(0, 16) }`)); // most significant bits (hex) uuidView.setBigUint64(8, BigInt(`0x${ uuid.substring(16) }`)); // least significant bits (hex) // read int32 for (let i = 0; i < 4; i++) { result[i] = uuidView.getInt32(i * 4, false); } return result; } /** * Takes an array with four int32 and return a string representation * that can be used for Minecraft 1.16+ commands (nbt) * * @param {number[]} uuidInt32 * * @returns {string} */ function formatInt32UUID(uuidInt32) { return `[I;${ uuidInt32[0] },${ uuidInt32[1] },${ uuidInt32[2] },${ uuidInt32[3] }]`; }
redirect old gallery route
js/base.script.js
redirect old gallery route
<ide><path>s/base.script.js <ide> } <ide> } <ide> }) <add> .state("gallery_legacy", { <add> url: "/gallery/:page?query", <add> redirectTo: "gallery" <add> }) <ide> .state("gallery", { <del> url: "/gallery/:page?query", <del> params: { <del> page: {value: "1"} <del> }, <add> url: "/gallery?query", <ide> views: { <ide> 'tab1': {}, <ide> 'tab2': {
Java
apache-2.0
a1043b87431cb62780181fbed71bc9b235d5b301
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import lhpn2sbml.parser.LHPNFile; import lhpn2sbml.gui.*; import graph.Graph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.Point; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseWheelEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //import java.awt.event.FocusEvent; //import java.awt.event.FocusListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; //import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JViewport; import tabs.CloseAndMaxTabbedPane; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import learn.LearnLHPN; import synthesis.Synthesis; import verification.Verification; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; //import datamanager.DataManagerLHPN; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenuBar menuBar; private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu, viewModel; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem newCsp; // The new csp menu item private JMenuItem newHse; // The new handshaking extension menu item private JMenuItem newUnc; // The new extended burst mode menu item private JMenuItem newRsg; // The new rsg menu item private JMenuItem newSpice; // The new spice circuit item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importLhpn; // The import lhpn menu item private JMenuItem importCsp; // The import csp menu item private JMenuItem importHse; // The import handshaking extension menu // item private JMenuItem importUnc; // The import extended burst mode menu item private JMenuItem importRsg; // The import rsg menu item private JMenuItem importSpice; // The import spice circuit item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng, exportSvg, exportTsd; private String root; // The root directory private FileTree tree; // FileTree private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools private JToolBar toolbar; // Tool bar for common options private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool // Bar // options private JPanel mainPanel; // the main panel public Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units, viewerCheck; private JTextField viewerField; private JLabel viewerLabel; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema, atacs, async, externView, treeSelected = false; private String viewer; private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml, saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace, viewLog, saveParam, saveSbml, saveTemp, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema, boolean atacs) { this.lema = lema; this.atacs = atacs; async = lema || atacs; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame if (lema) { frame = new JFrame("LEMA"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } else if (atacs) { frame = new JFrame("ATACS"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } else { frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); popup = new JPopupMenu(); // Sets up the Tool Bar toolbar = new JToolBar(); String imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "save.png"; saveButton = makeToolButton(imgName, "save", "Save", "Save"); // toolButton = new JButton("Save"); toolbar.add(saveButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "saveas.png"; saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As"); toolbar.add(saveasButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); // toolButton = new JButton("Run"); toolbar.add(runButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "savecheck.png"; checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check"); toolbar.add(checkButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "export.jpg"; exportButton = makeToolButton(imgName, "export", "Export", "Export"); toolbar.add(exportButton); saveButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); saveasButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // Creates a menu for the frame menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); importMenu = new JMenu("Import"); exportMenu = new JMenu("Export"); newMenu = new JMenu("New"); saveAsMenu = new JMenu("Save As"); view = new JMenu("View"); viewModel = new JMenu("Model"); tools = new JMenu("Tools"); menuBar.add(file); menuBar.add(edit); menuBar.add(view); menuBar.add(tools); menuBar.add(help); // menuBar.addFocusListener(this); // menuBar.addMouseListener(this); // file.addMouseListener(this); // edit.addMouseListener(this); // view.addMouseListener(this); // tools.addMouseListener(this); // help.addMouseListener(this); copy = new JMenuItem("Copy"); rename = new JMenuItem("Rename"); delete = new JMenuItem("Delete"); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); close = new JMenuItem("Close"); closeAll = new JMenuItem("Close All"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newSpice = new JMenuItem("Spice Circuit"); if (lema) { newVhdl = new JMenuItem("VHDL-AMS Model"); newLhpn = new JMenuItem("Labeled Hybrid Petri Net"); } else { newVhdl = new JMenuItem("VHDL Model"); newLhpn = new JMenuItem("Petri Net"); } newCsp = new JMenuItem("CSP Model"); newHse = new JMenuItem("Handshaking Expansion"); newUnc = new JMenuItem("Extended Burst Mode Machine"); newRsg = new JMenuItem("Reduced State Graph"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Histogram"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); if (lema) { importVhdl = new JMenuItem("VHDL-AMS Model"); importLhpn = new JMenuItem("Labeled Hybrid Petri Net"); } else { importVhdl = new JMenuItem("VHDL Model"); importLhpn = new JMenuItem("Petri Net"); } importSpice = new JMenuItem("Spice Circuit"); importCsp = new JMenuItem("CSP Model"); importHse = new JMenuItem("Handshaking Expansion"); importUnc = new JMenuItem("Extended Burst Mode Machine"); importRsg = new JMenuItem("Reduced State Graph"); exportCsv = new JMenuItem("Comma Separated Values (csv)"); exportDat = new JMenuItem("Tab Delimited Data (dat)"); exportEps = new JMenuItem("Encapsulated Postscript (eps)"); exportJpg = new JMenuItem("JPEG (jpg)"); exportPdf = new JMenuItem("Portable Document Format (pdf)"); exportPng = new JMenuItem("Portable Network Graphics (png)"); exportSvg = new JMenuItem("Scalable Vector Graphics (svg)"); exportTsd = new JMenuItem("Time Series Data (tsd)"); save = new JMenuItem("Save"); saveAs = new JMenuItem("Save As"); saveAsGcm = new JMenuItem("Genetic Circuit Model"); saveAsGraph = new JMenuItem("Graph"); saveAsSbml = new JMenuItem("Save SBML Model"); saveAsTemplate = new JMenuItem("Save SBML Template"); saveAsLhpn = new JMenuItem("LHPN"); run = new JMenuItem("Save and Run"); check = new JMenuItem("Save and Check"); saveSbml = new JMenuItem("Save as SBML"); saveTemp = new JMenuItem("Save as SBML Template"); saveParam = new JMenuItem("Save Parameters"); refresh = new JMenuItem("Refresh"); export = new JMenuItem("Export"); viewCircuit = new JMenuItem("Circuit"); viewRules = new JMenuItem("Rules"); viewTrace = new JMenuItem("Trace"); viewLog = new JMenuItem("Log"); viewModGraph = new JMenuItem("Using GraphViz"); viewModBrowser = new JMenuItem("Using Browser"); createAnal = new JMenuItem("Analysis Tool"); createLearn = new JMenuItem("Learn Tool"); createSbml = new JMenuItem("Create SBML File"); createSynth = new JMenuItem("Synthesis Tool"); createVer = new JMenuItem("Verification Tool"); exit = new JMenuItem("Exit"); copy.addActionListener(this); rename.addActionListener(this); delete.addActionListener(this); openProj.addActionListener(this); close.addActionListener(this); closeAll.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newLhpn.addActionListener(this); newCsp.addActionListener(this); newHse.addActionListener(this); newUnc.addActionListener(this); newRsg.addActionListener(this); newSpice.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importLhpn.addActionListener(this); importCsp.addActionListener(this); importHse.addActionListener(this); importUnc.addActionListener(this); importRsg.addActionListener(this); importSpice.addActionListener(this); exportCsv.addActionListener(this); exportDat.addActionListener(this); exportEps.addActionListener(this); exportJpg.addActionListener(this); exportPdf.addActionListener(this); exportPng.addActionListener(this); exportSvg.addActionListener(this); exportTsd.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); saveAsSbml.addActionListener(this); saveAsTemplate.addActionListener(this); run.addActionListener(this); check.addActionListener(this); saveSbml.addActionListener(this); saveTemp.addActionListener(this); saveParam.addActionListener(this); export.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewModGraph.addActionListener(this); viewModBrowser.addActionListener(this); createAnal.addActionListener(this); createLearn.addActionListener(this); createSbml.addActionListener(this); createSynth.addActionListener(this); createVer.addActionListener(this); save.setActionCommand("save"); saveAs.setActionCommand("saveas"); run.setActionCommand("run"); check.setActionCommand("check"); refresh.setActionCommand("refresh"); export.setActionCommand("export"); if (lema) { viewModGraph.setActionCommand("viewModel"); } else { viewModGraph.setActionCommand("graph"); } viewModBrowser.setActionCommand("browse"); createLearn.setActionCommand("createLearn"); createSbml.setActionCommand("createSBML"); createSynth.setActionCommand("openSynth"); createVer.setActionCommand("openVerify"); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); // newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, // ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey)); closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK)); // saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, // ShortCutKey)); // newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey)); // newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, // ShortCutKey)); // newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, // ShortCutKey)); // about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, // ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey)); pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey)); viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)); refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); Action newAction = new NewAction(); Action saveAction = new SaveAction(); Action importAction = new ImportAction(); Action exportAction = new ExportAction(); Action modelAction = new ModelAction(); newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new"); newMenu.getActionMap().put("new", newAction); saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "save"); saveAsMenu.getActionMap().put("save", saveAction); importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "import"); importMenu.getActionMap().put("import", importAction); exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "export"); exportMenu.getActionMap().put("export", exportAction); viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "model"); viewModel.getActionMap().put("model", modelAction); // graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, // ShortCutKey)); // probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); // if (!lema) { // importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // } // else { // importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // } // importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, // ShortCutKey)); // importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); newMenu.setMnemonic(KeyEvent.VK_N); saveAsMenu.setMnemonic(KeyEvent.VK_A); importMenu.setMnemonic(KeyEvent.VK_I); exportMenu.setMnemonic(KeyEvent.VK_E); viewModel.setMnemonic(KeyEvent.VK_M); copy.setMnemonic(KeyEvent.VK_C); rename.setMnemonic(KeyEvent.VK_R); delete.setMnemonic(KeyEvent.VK_D); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); close.setMnemonic(KeyEvent.VK_W); newCircuit.setMnemonic(KeyEvent.VK_G); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); newSpice.setMnemonic(KeyEvent.VK_P); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_H); if (!async) { importDot.setMnemonic(KeyEvent.VK_G); } else { importLhpn.setMnemonic(KeyEvent.VK_L); } importSbml.setMnemonic(KeyEvent.VK_S); importVhdl.setMnemonic(KeyEvent.VK_V); importSpice.setMnemonic(KeyEvent.VK_P); save.setMnemonic(KeyEvent.VK_S); run.setMnemonic(KeyEvent.VK_R); check.setMnemonic(KeyEvent.VK_K); exportCsv.setMnemonic(KeyEvent.VK_C); exportEps.setMnemonic(KeyEvent.VK_E); exportDat.setMnemonic(KeyEvent.VK_D); exportJpg.setMnemonic(KeyEvent.VK_J); exportPdf.setMnemonic(KeyEvent.VK_F); exportPng.setMnemonic(KeyEvent.VK_G); exportSvg.setMnemonic(KeyEvent.VK_S); exportTsd.setMnemonic(KeyEvent.VK_T); pref.setMnemonic(KeyEvent.VK_P); viewModGraph.setMnemonic(KeyEvent.VK_G); viewModBrowser.setMnemonic(KeyEvent.VK_B); createAnal.setMnemonic(KeyEvent.VK_A); createLearn.setMnemonic(KeyEvent.VK_L); importDot.setEnabled(false); importSbml.setEnabled(false); importVhdl.setEnabled(false); importLhpn.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.setEnabled(false); importSpice.setEnabled(false); exportMenu.setEnabled(false); // exportCsv.setEnabled(false); // exportDat.setEnabled(false); // exportEps.setEnabled(false); // exportJpg.setEnabled(false); // exportPdf.setEnabled(false); // exportPng.setEnabled(false); // exportSvg.setEnabled(false); // exportTsd.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newLhpn.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); newSpice.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); run.setEnabled(false); check.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); saveParam.setEnabled(false); refresh.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); edit.add(copy); edit.add(rename); // edit.add(refresh); edit.add(delete); // edit.addSeparator(); // edit.add(pref); file.add(newMenu); newMenu.add(newProj); if (!async) { newMenu.add(newCircuit); newMenu.add(newModel); } else if (atacs) { newMenu.add(newVhdl); newMenu.add(newLhpn); newMenu.add(newCsp); newMenu.add(newHse); newMenu.add(newUnc); newMenu.add(newRsg); } else { newMenu.add(newVhdl); newMenu.add(newLhpn); newMenu.add(newSpice); } newMenu.add(graph); newMenu.add(probGraph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(close); file.add(closeAll); file.addSeparator(); file.add(save); // file.add(saveAsMenu); if (!async) { saveAsMenu.add(saveAsGcm); saveAsMenu.add(saveAsGraph); saveAsMenu.add(saveAsSbml); saveAsMenu.add(saveAsTemplate); } else { saveAsMenu.add(saveAsLhpn); saveAsMenu.add(saveAsGraph); } file.add(saveAs); if (!async) { file.add(saveAsSbml); file.add(saveAsTemplate); } file.add(saveParam); file.add(run); if (!async) { file.add(check); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importSbml); } else if (atacs) { importMenu.add(importVhdl); importMenu.add(importLhpn); importMenu.add(importCsp); importMenu.add(importHse); importMenu.add(importUnc); importMenu.add(importRsg); } else { importMenu.add(importVhdl); importMenu.add(importLhpn); importMenu.add(importSpice); } file.add(exportMenu); exportMenu.add(exportCsv); exportMenu.add(exportDat); exportMenu.add(exportEps); exportMenu.add(exportJpg); exportMenu.add(exportPdf); exportMenu.add(exportPng); exportMenu.add(exportSvg); exportMenu.add(exportTsd); file.addSeparator(); // file.add(save); // file.add(saveAs); // file.add(run); // file.add(check); // if (!lema) { // file.add(saveParam); // } // file.addSeparator(); // file.add(export); // if (!lema) { // file.add(saveSbml); // file.add(saveTemp); // } help.add(manual); externView = false; viewer = ""; if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { edit.addSeparator(); edit.add(pref); file.add(exit); file.addSeparator(); help.add(about); } view.add(viewCircuit); view.add(viewLog); if (async) { view.addSeparator(); view.add(viewRules); view.add(viewTrace); } view.addSeparator(); view.add(viewModel); viewModel.add(viewModGraph); viewModel.add(viewModBrowser); view.addSeparator(); view.add(refresh); if (!async) { tools.add(createAnal); } if (!atacs) { tools.add(createLearn); } if (atacs) { tools.add(createSynth); } if (async) { tools.add(createVer); } // else { // tools.add(createSbml); // } root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { // file.add(pref); // file.add(exit); help.add(about); } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.general.file_browser", "").equals("")) { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.useInterval", "").equals("")) { biosimrc.put("biosim.sim.useInterval", "Print Interval"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } if (biosimrc.get("biosim.learn.tn", "").equals("")) { biosimrc.put("biosim.learn.tn", "2"); } if (biosimrc.get("biosim.learn.tj", "").equals("")) { biosimrc.put("biosim.learn.tj", "2"); } if (biosimrc.get("biosim.learn.ti", "").equals("")) { biosimrc.put("biosim.learn.ti", "0.5"); } if (biosimrc.get("biosim.learn.bins", "").equals("")) { biosimrc.put("biosim.learn.bins", "4"); } if (biosimrc.get("biosim.learn.equaldata", "").equals("")) { biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins"); } if (biosimrc.get("biosim.learn.autolevels", "").equals("")) { biosimrc.put("biosim.learn.autolevels", "Auto"); } if (biosimrc.get("biosim.learn.ta", "").equals("")) { biosimrc.put("biosim.learn.ta", "1.15"); } if (biosimrc.get("biosim.learn.tr", "").equals("")) { biosimrc.put("biosim.learn.tr", "0.75"); } if (biosimrc.get("biosim.learn.tm", "").equals("")) { biosimrc.put("biosim.learn.tm", "0.0"); } if (biosimrc.get("biosim.learn.tt", "").equals("")) { biosimrc.put("biosim.learn.tt", "0.025"); } if (biosimrc.get("biosim.learn.debug", "").equals("")) { biosimrc.put("biosim.learn.debug", "0"); } if (biosimrc.get("biosim.learn.succpred", "").equals("")) { biosimrc.put("biosim.learn.succpred", "Successors"); } if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) { biosimrc.put("biosim.learn.findbaseprob", "False"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema, atacs); log = new Log(); tab = new CloseAndMaxTabbedPane(false, this); tab.setPreferredSize(new Dimension(1100, 550)); tab.getPaneUI().addMouseListener(this); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); mainPanel.add(toolbar, "North"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.getGlassPane().setVisible(true); frame.getGlassPane().addMouseListener(this); frame.getGlassPane().addMouseMotionListener(this); frame.getGlassPane().addMouseWheelListener(this); frame.addMouseListener(this); menuBar.addMouseListener(this); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; frame.setSize(frameSize); } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; frame.setSize(frameSize); } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(dispatcher); if (save(tab.getSelectedIndex()) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!async) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get( "biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get( "biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); choices = new String[] { "Print Interval", "Number Of Steps" }; JComboBox useInterval = new JComboBox(choices); useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); JPanel analysisLabels = new JPanel(new GridLayout(13, 1)); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(useInterval); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(13, 1)); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", "")); final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", "")); final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", "")); choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; final JComboBox bins = new JComboBox(choices); bins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" }; final JComboBox equaldata = new JComboBox(choices); equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", "")); choices = new String[] { "Auto", "User" }; final JComboBox autolevels = new JComboBox(choices); autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", "")); final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", "")); final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", "")); final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", "")); final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", "")); choices = new String[] { "0", "1", "2", "3" }; final JComboBox debug = new JComboBox(choices); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); choices = new String[] { "Successors", "Predecessors", "Both" }; final JComboBox succpred = new JComboBox(choices); succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", "")); choices = new String[] { "True", "False" }; final JComboBox findbaseprob = new JComboBox(choices); findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", "")); JPanel learnLabels = new JPanel(new GridLayout(13, 1)); learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):")); learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):")); learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):")); learnLabels.add(new JLabel("Number Of Bins:")); learnLabels.add(new JLabel("Divide Bins:")); learnLabels.add(new JLabel("Generate Levels:")); learnLabels.add(new JLabel("Ratio For Activation (Ta):")); learnLabels.add(new JLabel("Ratio For Repression (Tr):")); learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):")); learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):")); learnLabels.add(new JLabel("Debug Level:")); learnLabels.add(new JLabel("Successors Or Predecessors:")); learnLabels.add(new JLabel("Basic FindBaseProb:")); JPanel learnFields = new JPanel(new GridLayout(13, 1)); learnFields.add(tn); learnFields.add(tj); learnFields.add(ti); learnFields.add(bins); learnFields.add(equaldata); learnFields.add(autolevels); learnFields.add(ta); learnFields.add(tr); learnFields.add(tm); learnFields.add(tt); learnFields.add(debug); learnFields.add(succpred); learnFields.add(findbaseprob); JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); JPanel generalPrefs = new JPanel(new BorderLayout()); generalPrefs.add(dialog, "North"); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", dialog); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); prefTabs.addTab("Learn Preferences", learnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem()); biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); try { Integer.parseInt(tn.getText().trim()); biosimrc.put("biosim.learn.tn", tn.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(tj.getText().trim()); biosimrc.put("biosim.learn.tj", tj.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ti.getText().trim()); biosimrc.put("biosim.learn.ti", ti.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem()); biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem()); biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem()); try { Double.parseDouble(ta.getText().trim()); biosimrc.put("biosim.learn.ta", ta.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tr.getText().trim()); biosimrc.put("biosim.learn.tr", tr.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tm.getText().trim()); biosimrc.put("biosim.learn.tm", tm.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tt.getText().trim()); biosimrc.put("biosim.learn.tt", tt.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem()); biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem()); biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { JPanel prefPanel = new JPanel(new GridLayout(0, 2)); viewerLabel = new JLabel("External Editor for non-LHPN files:"); viewerField = new JTextField(""); viewerCheck = new JCheckBox("Use External Viewer"); viewerCheck.addActionListener(this); viewerCheck.setSelected(externView); viewerField.setText(viewer); viewerLabel.setEnabled(externView); viewerField.setEnabled(externView); prefPanel.add(viewerLabel); prefPanel.add(viewerField); prefPanel.add(viewerCheck); // Preferences biosimrc = Preferences.userRoot(); // JPanel vhdlPrefs = new JPanel(); // JPanel lhpnPrefs = new JPanel(); // JTabbedPane prefTabsNoLema = new JTabbedPane(); // prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); // prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { viewer = viewerField.getText(); } } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel version = new JLabel("Version 1.02", JLabel.CENTER); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(bioSim, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == viewerCheck) { externView = viewerCheck.isSelected(); viewerLabel.setEnabled(viewerCheck.isSelected()); viewerField.setEnabled(viewerCheck.isSelected()); } if (e.getSource() == viewCircuit) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } else if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).viewLhpn(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewCircuit(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewCircuit(); } } } else if (e.getSource() == viewLog) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { if (new File(root + separator + "atacs.log").exists()) { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame(), "No log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewLog(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewLog(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewLog(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); } } } else if (e.getSource() == saveParam) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).save(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); } else { ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(2)).save(); } } } else if (e.getSource() == saveSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("SBML"); } else if (e.getSource() == saveTemp) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("template"); } else if (e.getSource() == saveAsGcm) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("GCM"); } else if (e.getSource() == saveAsLhpn) { Component comp = tab.getSelectedComponent(); ((LHPNEditor) comp).save(); } else if (e.getSource() == saveAsGraph) { Component comp = tab.getSelectedComponent(); ((Graph) comp).save(); } else if (e.getSource() == saveAsSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML"); } else if (e.getSource() == saveAsTemplate) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML template"); } else if (e.getSource() == close && tab.getSelectedComponent() != null) { Component comp = tab.getSelectedComponent(); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), tab.getSelectedIndex()); } else if (e.getSource() == closeAll) { while (tab.getSelectedComponent() != null) { int index = tab.getSelectedIndex(); Component comp = tab.getComponent(index); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), index); } } else if (e.getSource() == viewRules) { Component comp = tab.getSelectedComponent(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).viewRules(); } else if (e.getSource() == viewTrace) { Component comp = tab.getSelectedComponent(); if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewTrace(); } else { ((Verification) array[0]).viewTrace(); } } } else if (e.getSource() == exportCsv) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(5); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5); } } else if (e.getSource() == exportDat) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(6); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(); } } else if (e.getSource() == exportEps) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(3); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3); } } else if (e.getSource() == exportJpg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(0); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0); } } else if (e.getSource() == exportPdf) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(2); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2); } } else if (e.getSource() == exportPng) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(1); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1); } } else if (e.getSource() == exportSvg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(4); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4); } } else if (e.getSource() == exportTsd) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(7); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7); } } else if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = ""; if (!async) { theFile = "iBioSim.html"; } else if (atacs) { theFile = "ATACS.html"; } else { theFile = "LEMA.html"; } String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { if (lema) { openLearnLHPN(); } else { openLearn(); } } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out .write(("synthesis.file=" + circuitFileNoPath + "\n") .getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + synthName; String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath; JPanel synthPane = new JPanel(); Synthesis synth = new Synthesis(work, circuitFile, log, this); // synth.addMouseListener(this); synthPane.add(synth); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD * Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(synthName, synthPane, "Synthesis"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the verify popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); // try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } /* * try { FileInputStream in = new FileInputStream(new * File(root + separator + circuitFileNoPath)); * FileOutputStream out = new FileOutputStream(new * File(root + separator + verName.trim() + separator + * circuitFileNoPath)); int read = in.read(); while * (read != -1) { out.write(read); read = in.read(); } * in.close(); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy * circuit file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); // String work = root + separator + verName; // log.addText(circuitFile); JPanel verPane = new JPanel(); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); // verify.addMouseListener(this); verify.save(); verPane.add(verify); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(verName, verPane, "Verification"); } // } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Verification View directory.", "Error", // JOptionPane.ERROR_MESSAGE); // } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected else if (e.getActionCommand().contains("delete") || e.getSource() == delete) { if (!tree.getFile().equals(root)) { if (new File(tree.getFile()).isDirectory()) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String[] dot = tree.getFile().split(separator); String sbmlFile = dot[dot.length - 1] .substring(0, dot[dot.length - 1].length() - 3) + "sbml"; // log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " " // + root // + separator + sbmlFile // + "\n"); // Runtime exec = Runtime.getRuntime(); // String filename = tree.getFile(); // String directory = ""; // String theFile = ""; // if (filename.lastIndexOf('/') >= 0) { // directory = filename.substring(0, // filename.lastIndexOf('/') + 1); // theFile = filename.substring(filename.lastIndexOf('/') + 1); // } // if (filename.lastIndexOf('\\') >= 0) { // directory = filename.substring(0, filename // .lastIndexOf('\\') + 1); // theFile = filename // .substring(filename.lastIndexOf('\\') + 1); // } // File work = new File(directory); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + sbmlFile); refreshTree(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(sbmlFile)) { updateOpenSBML(sbmlFile); tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null); addTab(sbmlFile, sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the save button is pressed on the Tool Bar else if (e.getActionCommand().equals("save")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).save(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).save("Save GCM"); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(false, "", true); } else if (comp instanceof Graph) { ((Graph) comp).save(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = ((JTabbedPane) comp).getSelectedIndex(); if (component instanceof Graph) { ((Graph) component).save(); } else if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } else if (component instanceof DataManager) { ((DataManager) component).saveChanges(((JTabbedPane) comp).getTitleAt(index)); } else if (component instanceof SBML_Editor) { ((SBML_Editor) component).save(false, "", true); } else if (component instanceof Reb2Sac) { ((Reb2Sac) component).save(); } } if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); } else if (comp.getName().equals("Synthesis")) { // ((Synthesis) tab.getSelectedComponent()).save(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); try { File output = new File(root + separator + fileName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + fileName); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the save as button is pressed on the Tool Bar else if (e.getActionCommand().equals("saveas")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter LHPN name:", "LHPN Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".g")) { newName = newName + ".g"; } ((LHPNEditor) comp).saveAs(newName); } else if (comp instanceof GCM2SBMLEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:", "GCM Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (newName.contains(".gcm")) { newName = newName.replace(".gcm", ""); } ((GCM2SBMLEditor) comp).saveAs(newName); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).saveAs(); } else if (comp instanceof Graph) { ((Graph) comp).saveAs(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).saveAs(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).saveAs(); } else if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).saveAs(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); String newName = ""; if (fileName.endsWith(".vhd")) { newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".vhd")) { newName = newName + ".vhd"; } } else if (fileName.endsWith(".csp")) { newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".csp")) { newName = newName + ".csp"; } } else if (fileName.endsWith(".hse")) { newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".hse")) { newName = newName + ".hse"; } } else if (fileName.endsWith(".unc")) { newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".unc")) { newName = newName + ".unc"; } } else if (fileName.endsWith(".rsg")) { newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".rsg")) { newName = newName + ".rsg"; } } try { File output = new File(root + separator + newName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + newName); File oldFile = new File(root + separator + fileName); oldFile.delete(); tab.setTitleAt(tab.getSelectedIndex(), newName); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the run button is selected on the tool bar else if (e.getActionCommand().equals("run")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) { index = i; break; } } if (component instanceof Graph) { if (index != -1) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton() .doClick(); } else { ((Graph) component).save(); ((Graph) component).run(); } } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); } else if (component instanceof SBML_Editor) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof Reb2Sac) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JPanel) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JScrollPane) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); new Thread((Verification) array[0]).start(); } else if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); ((Synthesis) array[0]).run(); } } } else if (e.getActionCommand().equals("refresh")) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).refresh(); } } } else if (e.getActionCommand().equals("check")) { Component comp = tab.getSelectedComponent(); if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(true, "", true); ((SBML_Editor) comp).check(); } } else if (e.getActionCommand().equals("export")) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).export(); } } } // if the new menu item is selected else if (e.getSource() == newProj) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New", -1); if (!filename.trim().equals("")) { filename = filename.trim(); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { new FileWriter(new File(filename + separator + ".prj")).close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } File f; if (root == null) { f = null; } else { f = new File(root); } String projDir = ""; if (e.getSource() == openProj) { projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1); } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } if (!projDir.equals("")) { if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f .getName(), this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(f.getName(), gcm, "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".xml"; } } else { simName += ".xml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { String f = new String(root + separator + simName); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName); SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null); // sbml.addMouseListener(this); addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 4) { if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "VHDL Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 1) { if (!lhpnName.substring(lhpnName.length() - 2).equals(".g")) { lhpnName += ".g"; } } else { lhpnName += ".g"; } String modelID = ""; if (lhpnName.length() > 1) { if (lhpnName.substring(lhpnName.length() - 2).equals(".g")) { modelID = lhpnName.substring(0, lhpnName.length() - 2); } else { modelID = lhpnName.substring(0, lhpnName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.delete(); f.createNewFile(); new LHPNFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } addTab(f.getName(), new LHPNEditor(root + separator, f.getName(), null, this, log), "LHPN Editor"); refreshTree(); } if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.createNewFile(); new LHPNFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log); // lhpn.addMouseListener(this); addTab(f.getName(), lhpn, "LHPN Editor"); refreshTree(); } // File f = new File(root + separator + lhpnName); // f.createNewFile(); // String[] command = { "emacs", f.getName() }; // Runtime.getRuntime().exec(command); // refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new csp menu item is selected else if (e.getSource() == newCsp) { if (root != null) { try { String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (cspName != null && !cspName.trim().equals("")) { cspName = cspName.trim(); if (cspName.length() > 3) { if (!cspName.substring(cspName.length() - 4).equals(".csp")) { cspName += ".csp"; } } else { cspName += ".csp"; } String modelID = ""; if (cspName.length() > 3) { if (cspName.substring(cspName.length() - 4).equals(".csp")) { modelID = cspName.substring(0, cspName.length() - 4); } else { modelID = cspName.substring(0, cspName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + cspName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + cspName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(cspName, scroll, "CSP Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new hse menu item is selected else if (e.getSource() == newHse) { if (root != null) { try { String hseName = JOptionPane.showInputDialog(frame, "Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (hseName != null && !hseName.trim().equals("")) { hseName = hseName.trim(); if (hseName.length() > 3) { if (!hseName.substring(hseName.length() - 4).equals(".hse")) { hseName += ".hse"; } } else { hseName += ".hse"; } String modelID = ""; if (hseName.length() > 3) { if (hseName.substring(hseName.length() - 4).equals(".hse")) { modelID = hseName.substring(0, hseName.length() - 4); } else { modelID = hseName.substring(0, hseName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + hseName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + hseName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(hseName, scroll, "HSE Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new unc menu item is selected else if (e.getSource() == newUnc) { if (root != null) { try { String uncName = JOptionPane.showInputDialog(frame, "Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (uncName != null && !uncName.trim().equals("")) { uncName = uncName.trim(); if (uncName.length() > 3) { if (!uncName.substring(uncName.length() - 4).equals(".unc")) { uncName += ".unc"; } } else { uncName += ".unc"; } String modelID = ""; if (uncName.length() > 3) { if (uncName.substring(uncName.length() - 4).equals(".unc")) { modelID = uncName.substring(0, uncName.length() - 4); } else { modelID = uncName.substring(0, uncName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + uncName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + uncName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(uncName, scroll, "UNC Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { if (root != null) { try { String rsgName = JOptionPane.showInputDialog(frame, "Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (rsgName != null && !rsgName.trim().equals("")) { rsgName = rsgName.trim(); if (rsgName.length() > 3) { if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) { rsgName += ".rsg"; } } else { rsgName += ".rsg"; } String modelID = ""; if (rsgName.length() > 3) { if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) { modelID = rsgName.substring(0, rsgName.length() - 4); } else { modelID = rsgName.substring(0, rsgName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + rsgName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + rsgName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(rsgName, scroll, "RSG Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newSpice) { if (root != null) { try { String spiceName = JOptionPane.showInputDialog(frame, "Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE); if (spiceName != null && !spiceName.trim().equals("")) { spiceName = spiceName.trim(); if (spiceName.length() > 3) { if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) { spiceName += ".cir"; } } else { spiceName += ".cir"; } String modelID = ""; if (spiceName.length() > 3) { if (spiceName.substring(spiceName.length() - 4).equals(".cir")) { modelID = spiceName.substring(0, spiceName.length() - 4); } else { modelID = spiceName.substring(0, spiceName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + spiceName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + spiceName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(spiceName, scroll, "Spice Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1); if (!filename.trim().equals("")) { if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim() + separator + s); if (document.getNumErrors() == 0) { if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append("--------------------------------------------------------------------------------------\n"); messageArea.append(s); messageArea .append("\n--------------------------------------------------------------------------------------\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // . // replace // ( // "." // , // ".\n" // ) // ; messageArea.append(i + ":" + error + "\n"); } } // FileOutputStream out = new // FileOutputStream(new File(root // + separator + s)); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + s); // String doc = // writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim()); if (document.getNumErrors() > 0) { JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // . // replace // ( // "." // , // ".\n" // ) // ; messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } // FileOutputStream out = new // FileOutputStream(new File(root // + separator + file[file.length - 1])); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + file[file.length - 1]); // String doc = // writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1); if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File((filename .trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()).equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import VHDL Model", -1); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals( ".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import lhpn menu item is selected else if (e.getSource() == importLhpn) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import LHPN", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); File work = new File(root); String oldName = root + separator + file[file.length - 1]; String newName = oldName.replace(".g", "_NEW.g"); Process atacs = Runtime.getRuntime().exec("atacs -llsl " + oldName, null, work); atacs.waitFor(); FileOutputStream old = new FileOutputStream(new File(oldName)); FileInputStream newFile = new FileInputStream(new File(newName)); int readNew = newFile.read(); while (readNew != -1) { old.write(readNew); readNew = newFile.read(); } old.close(); newFile.close(); new File(newName).delete(); refreshTree(); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import csp menu item is selected else if (e.getSource() == importCsp) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import CSP", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".csp")) { JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import hse menu item is selected else if (e.getSource() == importHse) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import HSE", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".hse")) { JOptionPane.showMessageDialog(frame, "You must select a valid handshaking expansion file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import unc menu item is selected else if (e.getSource() == importUnc) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import UNC", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".unc")) { JOptionPane.showMessageDialog(frame, "You must select a valid expanded burst mode machine file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import RSG", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".rsg")) { JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import spice menu item is selected else if (e.getSource() == importSpice) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import Spice Circuit", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".cir")) { JOptionPane.showMessageDialog(frame, "You must select a valid spice circuit file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName.trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName.trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); // try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; if (sbmlFileNoPath.endsWith(".vhd")) { try { File work = new File(root); Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work); sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".g"); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to generate LHPN from VHDL file!", "Error Generating File", JOptionPane.ERROR_MESSAGE); } } try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); if (lema) { out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes()); } else { out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); } out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); DataManager data = new DataManager(root + separator + lrnName, this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Data Manager"); if (lema) { LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } // learn.addMouseListener(this); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph; tsdGraph = new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(lrnName, lrnTab, null); } // } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Learn View directory.", "Error", // JOptionPane.ERROR_MESSAGE); // } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("viewModel")) { try { if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lvslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); view.waitFor(); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lcslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lhslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lxodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lsodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { if (!tree.getFile().equals(root)) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".xml"; } } else { copy += ".xml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".csp")) { copy += ".csp"; } } else { copy += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".hse")) { copy += ".hse"; } } else { copy += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".unc")) { copy += ".unc"; } } else { copy += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".rsg")) { copy += ".rsg"; } } else { copy += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(tree.getFile()); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc") || tree.getFile().substring( tree.getFile().length() - 4).equals(".rsg")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + // copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy + separator + ss); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss .substring(ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss .substring(ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { if (!tree.getFile().equals(root)) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".xml"; } } else { rename += ".xml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".csp")) { rename += ".csp"; } } else { rename += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".hse")) { rename += ".hse"; } } else { rename += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".unc")) { rename += ".unc"; } } else { rename += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".rsg")) { rename += ".rsg"; } } else { rename += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename.equals(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".gcm") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".vhd") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".csp") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".hse") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".unc") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".rsg")) { String oldName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) { updateViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn") .renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf") .renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb") .renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile() .substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring( tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring( tree.getFile().length() - 4).equals( ".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".vhd")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 1 && tree.getFile() .substring(tree.getFile().length() - 2).equals( ".g")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 2)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".csp")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".hse")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".unc")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".rsg")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)) .getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)) .getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)) .getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties .replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")) .renameTo(new File(properties)); } else if (c instanceof Graph) { // c.addMouseListener(this); Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("GCM Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1) .setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[i]); } recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); // panel.addMouseListener(this); if (tabName != null) { tab.getComponentAt(tab.getTabCount() - 1).setName(tabName); } else { tab.getComponentAt(tab.getTabCount() - 1).setName(name); } tab.setSelectedIndex(tab.getTabCount() - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index) { if (tab.getComponentAt(index).getName().contains(("GCM")) || tab.getComponentAt(index).getName().contains("LHPN")) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save("gcm"); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } else if (tab.getComponentAt(index) instanceof LHPNEditor) { LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() .equals("Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .contains("Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)); g.save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } } else if (tab.getComponentAt(index) instanceof JPanel) { if ((tab.getComponentAt(index)).getName().equals("Synthesis")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Synthesis) { if (((Synthesis) array[0]).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save synthesis option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (tab.getComponentAt(index).getName().equals("Verification")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Verification) { if (((Verification) array[0]).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save verification option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Verification) array[0]).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } return 1; } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Saves a circuit from a learn view to the project view */ public void saveLhpn(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { // log.addText(e.getSource().toString()); if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } else { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { int index = tab.getSelectedIndex(); enableTabMenu(index); if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this, null, null); // sbml.addMouseListener(this); addTab(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "VHDL Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } LHPNFile lhpn = new LHPNFile(log); if (new File(directory + theFile).length() > 0) { // log.addText("here"); lhpn.load(directory + theFile); // log.addText("there"); } // log.addText("load completed"); File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { // log.addText("make Editor"); LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log); // editor.addMouseListener(this); addTab(theFile, editor, "LHPN Editor"); // log.addText("Editor made"); } // String[] cmd = { "emacs", filename }; // Runtime.getRuntime().exec(cmd); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this lhpn file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "CSP Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "HSE Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "UNC Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "RSG Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Spice Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this spice file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities .convertPoint(glassPane, glassPanePoint, container); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); if (e != null) { deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e .getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e .getClickCount(), e.isPopupTrigger())); } if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } catch (Exception e1) { e1.printStackTrace(); } } } else { if (tree.getFile() != null) { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (!popup.isVisible()) { frame.getGlassPane().setVisible(true); } } } } public void mouseMoved(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } public void mouseWheelMoved(MouseWheelEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); } } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1] .length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, dot[dot.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile()); // document.setLevel(2); document.setLevelAndVersion(2, 3); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); * String doc = writer.writeToString(document); byte[] * output = doc.getBytes(); out.write(output); out.close(); * } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml * file to output location.", "Error", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName .trim(), log, simTab, null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (sbml1[sbml1.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, sbml1[sbml1.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); Learn learn = new Learn(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); // } /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openLearnLHPN() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); // } /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile .split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this); // synth.addMouseListener(this); synthPanel.add(synth); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, "Synthesis"); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel verPanel = new JPanel(); // String graphFile = ""; /* * if (new File(tree.getFile()).isDirectory()) { String[] list = new * File(tree.getFile()).list(); int run = 0; for (int i = 0; i < * list.length; i++) { if (!(new File(list[i]).isDirectory()) && * list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; * j++) { end = list[i].charAt(list[i].length() - j) + end; } if * (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) * { if (list[i].contains("run-")) { int tempNum = * Integer.parseInt(list[i].substring(4, list[i] .length() - * end.length())); if (tempNum > run) { run = tempNum; // graphFile * = tree.getFile() + separator + // list[i]; } } } } } } */ String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String verFile = tree.getFile() + separator + verName + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(verifyFile)); load.store(out, verifyFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(verFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Verification ver = new Verification(root + separator + verName, verName, "flag", log, this, lema, atacs); // ver.addMouseListener(this); verPanel.add(ver); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel, "Verification"); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + // s[j]; } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + // s[j]; } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; String gcmFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane .showMessageDialog( frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable * to load sbml file.", "Error", * JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1) .setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } // if (open != null) { Graph tsdGraph = reb2sac.createGraph(open); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "TSD Graph"); /* * } else if (!graphFile.equals("")) { * simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = * new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { Graph probGraph = reb2sac.createProbGraph(openProb); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Probability Graph", * reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = * new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); simTab.addTab("Probability * Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } private class NewAction extends AbstractAction { NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!async) { popup.add(newCircuit); popup.add(newModel); } else if (atacs) { popup.add(newVhdl); popup.add(newLhpn); popup.add(newCsp); popup.add(newHse); popup.add(newUnc); popup.add(newRsg); } else { popup.add(newVhdl); popup.add(newLhpn); popup.add(newSpice); } popup.add(graph); popup.add(probGraph); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class SaveAction extends AbstractAction { SaveAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(saveAsGcm); } else { popup.add(saveAsLhpn); } popup.add(saveAsGraph); if (!lema) { popup.add(saveAsSbml); popup.add(saveAsTemplate); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ImportAction extends AbstractAction { ImportAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(importDot); popup.add(importSbml); } else if (atacs) { popup.add(importVhdl); popup.add(importLhpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } else { popup.add(importVhdl); popup.add(importLhpn); popup.add(importSpice); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ExportAction extends AbstractAction { ExportAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(exportCsv); popup.add(exportDat); popup.add(exportEps); popup.add(exportJpg); popup.add(exportPdf); popup.add(exportPng); popup.add(exportSvg); popup.add(exportTsd); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ModelAction extends AbstractAction { ModelAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(viewModGraph); popup.add(viewModBrowser); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } public void mouseClicked(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } catch (Exception e1) { } } } public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } boolean lemaFlag = false, atacsFlag = false; if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-lema")) { lemaFlag = true; } else if (args[i].equals("-atacs")) { atacsFlag = true; } } } new BioSim(lemaFlag, atacsFlag); } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; String gcmFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSim + separator + ss); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File( root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals( "TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)) .refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)) .setComponentAt(j, new Graph(null, "amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName( "TSD Graph"); } /* * } else { JLabel noData1 = new JLabel("No data * available"); Font font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { if (lema) { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this)); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn( root + separator + learnName, log, this)); } ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) .setName("Learn"); } /* * } else { JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))) .getElementsPanel()); sim.getComponentAt(j + 1).setName(""); } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } private void enableTabMenu(int selectedTab) { treeSelected = false; // log.addText("tab menu"); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); // if (comp != null) { // log.addText(comp.toString()); // } viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); if (comp instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof LHPNEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(true); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(true); viewLog.setEnabled(false); saveParam.setEnabled(false); } else if (comp instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(true); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(true); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) comp).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Boolean learn = false; for (Component c : ((JTabbedPane) comp).getComponents()) { if (c instanceof Learn) { learn = true; } } // int index = tab.getSelectedIndex(); if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); if (learn) { runButton.setEnabled(false); } else { runButton.setEnabled(true); } refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); if (learn) { run.setEnabled(false); } else { run.setEnabled(true); } saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) component).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Reb2Sac) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (((Learn) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((Learn) component).getSaveGcmEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((Learn) component).getSaveGcmEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { if (((LearnLHPN) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JPanel) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewRules.setEnabled(false); // viewTrace.setEnabled(((Verification) // comp).getViewTraceEnabled()); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); // viewLog.setEnabled(((Verification) // comp).getViewLogEnabled()); viewLog.setEnabled(true); saveParam.setEnabled(true); } else if (comp.getName().equals("Synthesis")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); // viewRules.setEnabled(((Synthesis) // comp).getViewRulesEnabled()); // viewTrace.setEnabled(((Synthesis) // comp).getViewTraceEnabled()); // viewCircuit.setEnabled(((Synthesis) // comp).getViewCircuitEnabled()); // viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewRules.setEnabled(true); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); viewLog.setEnabled(true); saveParam.setEnabled(false); } } else if (comp instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else { saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); } private void enableTreeMenu() { treeSelected = true; // log.addText(tree.getFile()); saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); exportMenu.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); if (tree.getFile() != null) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graph"); viewModBrowser.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("simulate"); createLearn.setEnabled(true); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graphDot"); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSbml.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim || synth || ver || learn) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { frame.getGlassPane().setVisible(visible); } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; // int value = JOptionPane.showOptionDialog(frame, name + " already // exists." // + "\nDo you want to overwrite?", "Overwrite", // JOptionPane.YES_NO_OPTION, // JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } // } // else { // return false; // } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText, String altText) { // URL imageURL = BioSim.class.getResource(imageName); // Create and initialize the button. JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); button.setIcon(new ImageIcon(imageName)); // if (imageURL != null) { //image found // button.setIcon(new ImageIcon(imageURL, altText)); // } else { //no image found // button.setText(altText); // System.err.println("Resource not found: " // + imageName); // } return button; } }
gui/src/biomodelsim/BioSim.java
package biomodelsim; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.network.GeneticNetwork; import gcm2sbml.parser.CompatibilityFixer; import gcm2sbml.parser.GCMFile; import gcm2sbml.parser.GCMParser; import gcm2sbml.util.GlobalConstants; import lhpn2sbml.parser.LHPNFile; import lhpn2sbml.gui.*; import graph.Graph; import java.awt.AWTError; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import java.awt.Point; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.MouseWheelEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //import java.awt.event.FocusEvent; //import java.awt.event.FocusListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; import java.util.prefs.Preferences; import java.util.regex.Pattern; //import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JViewport; import tabs.CloseAndMaxTabbedPane; import com.apple.eawt.ApplicationAdapter; import com.apple.eawt.ApplicationEvent; import com.apple.eawt.Application; import learn.Learn; import learn.LearnLHPN; import synthesis.Synthesis; import verification.Verification; import org.sbml.libsbml.Compartment; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.SBMLReader; import org.sbml.libsbml.SBMLWriter; import reb2sac.Reb2Sac; import reb2sac.Run; import sbmleditor.SBML_Editor; import buttons.Buttons; import datamanager.DataManager; //import datamanager.DataManagerLHPN; /** * This class creates a GUI for the Tstubd program. It implements the * ActionListener class. This allows the GUI to perform actions when menu items * are selected. * * @author Curtis Madsen */ public class BioSim implements MouseListener, ActionListener, MouseMotionListener, MouseWheelListener { private JFrame frame; // Frame where components of the GUI are displayed private JMenuBar menuBar; private JMenu file, edit, view, tools, help, saveAsMenu, importMenu, exportMenu, newMenu, viewModel; // The file menu private JMenuItem newProj; // The new menu item private JMenuItem newModel; // The new menu item private JMenuItem newCircuit; // The new menu item private JMenuItem newVhdl; // The new vhdl menu item private JMenuItem newLhpn; // The new lhpn menu item private JMenuItem newCsp; // The new csp menu item private JMenuItem newHse; // The new handshaking extension menu item private JMenuItem newUnc; // The new extended burst mode menu item private JMenuItem newRsg; // The new rsg menu item private JMenuItem newSpice; // The new spice circuit item private JMenuItem exit; // The exit menu item private JMenuItem importSbml; // The import sbml menu item private JMenuItem importDot; // The import dot menu item private JMenuItem importVhdl; // The import vhdl menu item private JMenuItem importLhpn; // The import lhpn menu item private JMenuItem importCsp; // The import csp menu item private JMenuItem importHse; // The import handshaking extension menu // item private JMenuItem importUnc; // The import extended burst mode menu item private JMenuItem importRsg; // The import rsg menu item private JMenuItem importSpice; // The import spice circuit item private JMenuItem manual; // The manual menu item private JMenuItem about; // The about menu item private JMenuItem openProj; // The open menu item private JMenuItem pref; // The preferences menu item private JMenuItem graph; // The graph menu item private JMenuItem probGraph, exportCsv, exportDat, exportEps, exportJpg, exportPdf, exportPng, exportSvg, exportTsd; private String root; // The root directory private FileTree tree; // FileTree private CloseAndMaxTabbedPane tab; // JTabbedPane for different tools private JToolBar toolbar; // Tool bar for common options private JButton saveButton, runButton, refreshButton, saveasButton, checkButton, exportButton; // Tool // Bar // options private JPanel mainPanel; // the main panel public Log log; // the log private JPopupMenu popup; // popup menu private String separator; private KeyEventDispatcher dispatcher; private JMenuItem recentProjects[]; private String recentProjectPaths[]; private int numberRecentProj; private int ShortCutKey; public boolean checkUndeclared, checkUnits; private JCheckBox Undeclared, Units, viewerCheck; private JTextField viewerField; private JLabel viewerLabel; private Pattern IDpat = Pattern.compile("([a-zA-Z]|_)([a-zA-Z]|[0-9]|_)*"); private boolean lema, atacs, async, externView, treeSelected = false; private String viewer; private JMenuItem copy, rename, delete, save, saveAs, saveAsGcm, saveAsGraph, saveAsSbml, saveAsTemplate, saveAsLhpn, check, run, export, refresh, viewCircuit, viewRules, viewTrace, viewLog, saveParam, saveSbml, saveTemp, viewModGraph, viewModBrowser, createAnal, createLearn, createSbml, createSynth, createVer, close, closeAll; public class MacOSAboutHandler extends Application { public MacOSAboutHandler() { addApplicationListener(new AboutBoxHandler()); } class AboutBoxHandler extends ApplicationAdapter { public void handleAbout(ApplicationEvent event) { about(); event.setHandled(true); } } } public class MacOSPreferencesHandler extends Application { public MacOSPreferencesHandler() { addApplicationListener(new PreferencesHandler()); } class PreferencesHandler extends ApplicationAdapter { public void handlePreferences(ApplicationEvent event) { preferences(); event.setHandled(true); } } } public class MacOSQuitHandler extends Application { public MacOSQuitHandler() { addApplicationListener(new QuitHandler()); } class QuitHandler extends ApplicationAdapter { public void handleQuit(ApplicationEvent event) { exit(); event.setHandled(true); } } } /** * This is the constructor for the Proj class. It initializes all the input * fields, puts them on panels, adds the panels to the frame, and then * displays the frame. * * @throws Exception */ public BioSim(boolean lema, boolean atacs) { this.lema = lema; this.atacs = atacs; async = lema || atacs; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } // Creates a new frame if (lema) { frame = new JFrame("LEMA"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } else if (atacs) { frame = new JFrame("ATACS"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } else { frame = new JFrame("iBioSim"); frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + separator + "gui" + separator + "icons" + separator + "iBioSim.png").getImage()); } // Makes it so that clicking the x in the corner closes the program WindowListener w = new WindowListener() { public void windowClosing(WindowEvent arg0) { exit.doClick(); } public void windowOpened(WindowEvent arg0) { } public void windowClosed(WindowEvent arg0) { } public void windowIconified(WindowEvent arg0) { } public void windowDeiconified(WindowEvent arg0) { } public void windowActivated(WindowEvent arg0) { } public void windowDeactivated(WindowEvent arg0) { } }; frame.addWindowListener(w); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); popup = new JPopupMenu(); // Sets up the Tool Bar toolbar = new JToolBar(); String imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "save.png"; saveButton = makeToolButton(imgName, "save", "Save", "Save"); // toolButton = new JButton("Save"); toolbar.add(saveButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "saveas.png"; saveasButton = makeToolButton(imgName, "saveas", "Save As", "Save As"); toolbar.add(saveasButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "run-icon.jpg"; runButton = makeToolButton(imgName, "run", "Save and Run", "Run"); // toolButton = new JButton("Run"); toolbar.add(runButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "refresh.jpg"; refreshButton = makeToolButton(imgName, "refresh", "Refresh", "Refresh"); toolbar.add(refreshButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "savecheck.png"; checkButton = makeToolButton(imgName, "check", "Save and Check", "Save and Check"); toolbar.add(checkButton); imgName = System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "export.jpg"; exportButton = makeToolButton(imgName, "export", "Export", "Export"); toolbar.add(exportButton); saveButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); saveasButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); // Creates a menu for the frame menuBar = new JMenuBar(); file = new JMenu("File"); file.setMnemonic(KeyEvent.VK_F); help = new JMenu("Help"); help.setMnemonic(KeyEvent.VK_H); edit = new JMenu("Edit"); edit.setMnemonic(KeyEvent.VK_E); importMenu = new JMenu("Import"); exportMenu = new JMenu("Export"); newMenu = new JMenu("New"); saveAsMenu = new JMenu("Save As"); view = new JMenu("View"); viewModel = new JMenu("Model"); tools = new JMenu("Tools"); menuBar.add(file); menuBar.add(edit); menuBar.add(view); menuBar.add(tools); menuBar.add(help); // menuBar.addFocusListener(this); // menuBar.addMouseListener(this); // file.addMouseListener(this); // edit.addMouseListener(this); // view.addMouseListener(this); // tools.addMouseListener(this); // help.addMouseListener(this); copy = new JMenuItem("Copy"); rename = new JMenuItem("Rename"); delete = new JMenuItem("Delete"); manual = new JMenuItem("Manual"); about = new JMenuItem("About"); openProj = new JMenuItem("Open Project"); close = new JMenuItem("Close"); closeAll = new JMenuItem("Close All"); pref = new JMenuItem("Preferences"); newProj = new JMenuItem("Project"); newCircuit = new JMenuItem("Genetic Circuit Model"); newModel = new JMenuItem("SBML Model"); newSpice = new JMenuItem("Spice Circuit"); if (lema) { newVhdl = new JMenuItem("VHDL-AMS Model"); newLhpn = new JMenuItem("Labeled Hybrid Petri Net"); } else { newVhdl = new JMenuItem("VHDL Model"); newLhpn = new JMenuItem("Petri Net"); } newCsp = new JMenuItem("CSP Model"); newHse = new JMenuItem("Handshaking Expansion"); newUnc = new JMenuItem("Extended Burst Mode Machine"); newRsg = new JMenuItem("Reduced State Graph"); graph = new JMenuItem("TSD Graph"); probGraph = new JMenuItem("Histogram"); importSbml = new JMenuItem("SBML Model"); importDot = new JMenuItem("Genetic Circuit Model"); if (lema) { importVhdl = new JMenuItem("VHDL-AMS Model"); importLhpn = new JMenuItem("Labeled Hybrid Petri Net"); } else { importVhdl = new JMenuItem("VHDL Model"); importLhpn = new JMenuItem("Petri Net"); } importSpice = new JMenuItem("Spice Circuit"); importCsp = new JMenuItem("CSP Model"); importHse = new JMenuItem("Handshaking Expansion"); importUnc = new JMenuItem("Extended Burst Mode Machine"); importRsg = new JMenuItem("Reduced State Graph"); exportCsv = new JMenuItem("Comma Separated Values (csv)"); exportDat = new JMenuItem("Tab Delimited Data (dat)"); exportEps = new JMenuItem("Encapsulated Postscript (eps)"); exportJpg = new JMenuItem("JPEG (jpg)"); exportPdf = new JMenuItem("Portable Document Format (pdf)"); exportPng = new JMenuItem("Portable Network Graphics (png)"); exportSvg = new JMenuItem("Scalable Vector Graphics (svg)"); exportTsd = new JMenuItem("Time Series Data (tsd)"); save = new JMenuItem("Save"); saveAs = new JMenuItem("Save As"); saveAsGcm = new JMenuItem("Genetic Circuit Model"); saveAsGraph = new JMenuItem("Graph"); saveAsSbml = new JMenuItem("Save SBML Model"); saveAsTemplate = new JMenuItem("Save SBML Template"); saveAsLhpn = new JMenuItem("LHPN"); run = new JMenuItem("Save and Run"); check = new JMenuItem("Save and Check"); saveSbml = new JMenuItem("Save as SBML"); saveTemp = new JMenuItem("Save as SBML Template"); saveParam = new JMenuItem("Save Parameters"); refresh = new JMenuItem("Refresh"); export = new JMenuItem("Export"); viewCircuit = new JMenuItem("Circuit"); viewRules = new JMenuItem("Rules"); viewTrace = new JMenuItem("Trace"); viewLog = new JMenuItem("Log"); viewModGraph = new JMenuItem("Using GraphViz"); viewModBrowser = new JMenuItem("Using Browser"); createAnal = new JMenuItem("Analysis Tool"); createLearn = new JMenuItem("Learn Tool"); createSbml = new JMenuItem("Create SBML File"); createSynth = new JMenuItem("Synthesis Tool"); createVer = new JMenuItem("Verification Tool"); exit = new JMenuItem("Exit"); copy.addActionListener(this); rename.addActionListener(this); delete.addActionListener(this); openProj.addActionListener(this); close.addActionListener(this); closeAll.addActionListener(this); pref.addActionListener(this); manual.addActionListener(this); newProj.addActionListener(this); newCircuit.addActionListener(this); newModel.addActionListener(this); newVhdl.addActionListener(this); newLhpn.addActionListener(this); newCsp.addActionListener(this); newHse.addActionListener(this); newUnc.addActionListener(this); newRsg.addActionListener(this); newSpice.addActionListener(this); exit.addActionListener(this); about.addActionListener(this); importSbml.addActionListener(this); importDot.addActionListener(this); importVhdl.addActionListener(this); importLhpn.addActionListener(this); importCsp.addActionListener(this); importHse.addActionListener(this); importUnc.addActionListener(this); importRsg.addActionListener(this); importSpice.addActionListener(this); exportCsv.addActionListener(this); exportDat.addActionListener(this); exportEps.addActionListener(this); exportJpg.addActionListener(this); exportPdf.addActionListener(this); exportPng.addActionListener(this); exportSvg.addActionListener(this); exportTsd.addActionListener(this); graph.addActionListener(this); probGraph.addActionListener(this); save.addActionListener(this); saveAs.addActionListener(this); saveAsSbml.addActionListener(this); saveAsTemplate.addActionListener(this); run.addActionListener(this); check.addActionListener(this); saveSbml.addActionListener(this); saveTemp.addActionListener(this); saveParam.addActionListener(this); export.addActionListener(this); viewCircuit.addActionListener(this); viewRules.addActionListener(this); viewTrace.addActionListener(this); viewLog.addActionListener(this); viewModGraph.addActionListener(this); viewModBrowser.addActionListener(this); createAnal.addActionListener(this); createLearn.addActionListener(this); createSbml.addActionListener(this); createSynth.addActionListener(this); createVer.addActionListener(this); save.setActionCommand("save"); saveAs.setActionCommand("saveas"); run.setActionCommand("run"); check.setActionCommand("check"); refresh.setActionCommand("refresh"); export.setActionCommand("export"); if (lema) { viewModGraph.setActionCommand("viewModel"); } else { viewModGraph.setActionCommand("graph"); } viewModBrowser.setActionCommand("browse"); createLearn.setActionCommand("createLearn"); createSbml.setActionCommand("createSBML"); createSynth.setActionCommand("openSynth"); createVer.setActionCommand("openVerify"); ShortCutKey = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ShortCutKey)); rename.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0)); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ShortCutKey)); // newProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, // ShortCutKey)); openProj.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ShortCutKey)); close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey)); closeAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortCutKey | KeyEvent.SHIFT_MASK)); // saveAsMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // importMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // exportMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // viewModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, // ShortCutKey | KeyEvent.ALT_DOWN_MASK)); // newCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, // ShortCutKey)); // newModel.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, // ShortCutKey)); // newVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, // ShortCutKey)); // newLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, // ShortCutKey)); // about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, // ShortCutKey)); manual.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey)); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey)); run.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ShortCutKey)); check.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ShortCutKey)); pref.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, ShortCutKey)); viewCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); viewLog.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0)); refresh.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0)); createAnal.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ShortCutKey)); createLearn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ShortCutKey)); Action newAction = new NewAction(); Action saveAction = new SaveAction(); Action importAction = new ImportAction(); Action exportAction = new ExportAction(); Action modelAction = new ModelAction(); newMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_N, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "new"); newMenu.getActionMap().put("new", newAction); saveAsMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_S, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "save"); saveAsMenu.getActionMap().put("save", saveAction); importMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_I, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "import"); importMenu.getActionMap().put("import", importAction); exportMenu.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_E, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "export"); exportMenu.getActionMap().put("export", exportAction); viewModel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( KeyStroke.getKeyStroke(KeyEvent.VK_M, ShortCutKey | KeyEvent.ALT_DOWN_MASK), "model"); viewModel.getActionMap().put("model", modelAction); // graph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, // ShortCutKey)); // probGraph.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); // if (!lema) { // importDot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // } // else { // importLhpn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, // ShortCutKey)); // } // importSbml.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, // ShortCutKey)); // importVhdl.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, // ShortCutKey)); newMenu.setMnemonic(KeyEvent.VK_N); saveAsMenu.setMnemonic(KeyEvent.VK_A); importMenu.setMnemonic(KeyEvent.VK_I); exportMenu.setMnemonic(KeyEvent.VK_E); viewModel.setMnemonic(KeyEvent.VK_M); copy.setMnemonic(KeyEvent.VK_C); rename.setMnemonic(KeyEvent.VK_R); delete.setMnemonic(KeyEvent.VK_D); exit.setMnemonic(KeyEvent.VK_X); newProj.setMnemonic(KeyEvent.VK_P); openProj.setMnemonic(KeyEvent.VK_O); close.setMnemonic(KeyEvent.VK_W); newCircuit.setMnemonic(KeyEvent.VK_G); newModel.setMnemonic(KeyEvent.VK_S); newVhdl.setMnemonic(KeyEvent.VK_V); newLhpn.setMnemonic(KeyEvent.VK_L); newSpice.setMnemonic(KeyEvent.VK_P); about.setMnemonic(KeyEvent.VK_A); manual.setMnemonic(KeyEvent.VK_M); graph.setMnemonic(KeyEvent.VK_T); probGraph.setMnemonic(KeyEvent.VK_H); if (!async) { importDot.setMnemonic(KeyEvent.VK_G); } else { importLhpn.setMnemonic(KeyEvent.VK_L); } importSbml.setMnemonic(KeyEvent.VK_S); importVhdl.setMnemonic(KeyEvent.VK_V); importSpice.setMnemonic(KeyEvent.VK_P); save.setMnemonic(KeyEvent.VK_S); run.setMnemonic(KeyEvent.VK_R); check.setMnemonic(KeyEvent.VK_K); exportCsv.setMnemonic(KeyEvent.VK_C); exportEps.setMnemonic(KeyEvent.VK_E); exportDat.setMnemonic(KeyEvent.VK_D); exportJpg.setMnemonic(KeyEvent.VK_J); exportPdf.setMnemonic(KeyEvent.VK_F); exportPng.setMnemonic(KeyEvent.VK_G); exportSvg.setMnemonic(KeyEvent.VK_S); exportTsd.setMnemonic(KeyEvent.VK_T); pref.setMnemonic(KeyEvent.VK_P); viewModGraph.setMnemonic(KeyEvent.VK_G); viewModBrowser.setMnemonic(KeyEvent.VK_B); createAnal.setMnemonic(KeyEvent.VK_A); createLearn.setMnemonic(KeyEvent.VK_L); importDot.setEnabled(false); importSbml.setEnabled(false); importVhdl.setEnabled(false); importLhpn.setEnabled(false); importCsp.setEnabled(false); importHse.setEnabled(false); importUnc.setEnabled(false); importRsg.setEnabled(false); importSpice.setEnabled(false); exportMenu.setEnabled(false); // exportCsv.setEnabled(false); // exportDat.setEnabled(false); // exportEps.setEnabled(false); // exportJpg.setEnabled(false); // exportPdf.setEnabled(false); // exportPng.setEnabled(false); // exportSvg.setEnabled(false); // exportTsd.setEnabled(false); newCircuit.setEnabled(false); newModel.setEnabled(false); newVhdl.setEnabled(false); newLhpn.setEnabled(false); newCsp.setEnabled(false); newHse.setEnabled(false); newUnc.setEnabled(false); newRsg.setEnabled(false); newSpice.setEnabled(false); graph.setEnabled(false); probGraph.setEnabled(false); save.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); run.setEnabled(false); check.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); saveParam.setEnabled(false); refresh.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); edit.add(copy); edit.add(rename); // edit.add(refresh); edit.add(delete); // edit.addSeparator(); // edit.add(pref); file.add(newMenu); newMenu.add(newProj); if (!async) { newMenu.add(newCircuit); newMenu.add(newModel); } else if (atacs) { newMenu.add(newVhdl); newMenu.add(newLhpn); newMenu.add(newCsp); newMenu.add(newHse); newMenu.add(newUnc); newMenu.add(newRsg); } else { newMenu.add(newVhdl); newMenu.add(newLhpn); newMenu.add(newSpice); } newMenu.add(graph); newMenu.add(probGraph); file.add(openProj); // openMenu.add(openProj); file.addSeparator(); file.add(close); file.add(closeAll); file.addSeparator(); file.add(save); // file.add(saveAsMenu); if (!async) { saveAsMenu.add(saveAsGcm); saveAsMenu.add(saveAsGraph); saveAsMenu.add(saveAsSbml); saveAsMenu.add(saveAsTemplate); } else { saveAsMenu.add(saveAsLhpn); saveAsMenu.add(saveAsGraph); } file.add(saveAs); if (!async) { file.add(saveAsSbml); file.add(saveAsTemplate); } file.add(saveParam); file.add(run); if (!async) { file.add(check); } file.addSeparator(); file.add(importMenu); if (!async) { importMenu.add(importDot); importMenu.add(importSbml); } else if (atacs) { importMenu.add(importVhdl); importMenu.add(importLhpn); importMenu.add(importCsp); importMenu.add(importHse); importMenu.add(importUnc); importMenu.add(importRsg); } else { importMenu.add(importVhdl); importMenu.add(importLhpn); importMenu.add(importSpice); } file.add(exportMenu); exportMenu.add(exportCsv); exportMenu.add(exportDat); exportMenu.add(exportEps); exportMenu.add(exportJpg); exportMenu.add(exportPdf); exportMenu.add(exportPng); exportMenu.add(exportSvg); exportMenu.add(exportTsd); file.addSeparator(); // file.add(save); // file.add(saveAs); // file.add(run); // file.add(check); // if (!lema) { // file.add(saveParam); // } // file.addSeparator(); // file.add(export); // if (!lema) { // file.add(saveSbml); // file.add(saveTemp); // } help.add(manual); externView = false; viewer = ""; if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { edit.addSeparator(); edit.add(pref); file.add(exit); file.addSeparator(); help.add(about); } view.add(viewCircuit); view.add(viewLog); if (async) { view.addSeparator(); view.add(viewRules); view.add(viewTrace); } view.addSeparator(); view.add(viewModel); viewModel.add(viewModGraph); viewModel.add(viewModBrowser); view.addSeparator(); view.add(refresh); if (!async) { tools.add(createAnal); } if (!atacs) { tools.add(createLearn); } if (atacs) { tools.add(createSynth); } if (async) { tools.add(createVer); } // else { // tools.add(createSbml); // } root = null; // Create recent project menu items numberRecentProj = 0; recentProjects = new JMenuItem[5]; recentProjectPaths = new String[5]; for (int i = 0; i < 5; i++) { recentProjects[i] = new JMenuItem(); recentProjects[i].addActionListener(this); recentProjectPaths[i] = ""; } recentProjects[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ShortCutKey)); recentProjects[0].setMnemonic(KeyEvent.VK_1); recentProjects[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ShortCutKey)); recentProjects[1].setMnemonic(KeyEvent.VK_2); recentProjects[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ShortCutKey)); recentProjects[2].setMnemonic(KeyEvent.VK_3); recentProjects[3].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ShortCutKey)); recentProjects[3].setMnemonic(KeyEvent.VK_4); recentProjects[4].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ShortCutKey)); recentProjects[4].setMnemonic(KeyEvent.VK_5); Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < 5; i++) { recentProjects[i].setText(biosimrc.get("biosim.recent.project." + i, "")); recentProjectPaths[i] = biosimrc.get("biosim.recent.project.path." + i, ""); if (!recentProjectPaths[i].equals("")) { file.add(recentProjects[i]); numberRecentProj = i + 1; } } if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { new MacOSAboutHandler(); new MacOSPreferencesHandler(); new MacOSQuitHandler(); Application application = new Application(); application.addPreferencesMenuItem(); application.setEnabledPreferencesMenu(true); } else { // file.add(pref); // file.add(exit); help.add(about); } if (biosimrc.get("biosim.check.undeclared", "").equals("false")) { checkUndeclared = false; } else { checkUndeclared = true; } if (biosimrc.get("biosim.check.units", "").equals("false")) { checkUnits = false; } else { checkUnits = true; } if (biosimrc.get("biosim.general.file_browser", "").equals("")) { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (biosimrc.get("biosim.gcm.KREP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KREP_VALUE", ".5"); } if (biosimrc.get("biosim.gcm.KACT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KACT_VALUE", ".0033"); } if (biosimrc.get("biosim.gcm.KBIO_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBIO_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.PROMOTER_COUNT_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", "2"); } if (biosimrc.get("biosim.gcm.KASSOCIATION_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KBASAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KBASAL_VALUE", ".0001"); } if (biosimrc.get("biosim.gcm.OCR_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.OCR_VALUE", ".05"); } if (biosimrc.get("biosim.gcm.KDECAY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.KDECAY_VALUE", ".0075"); } if (biosimrc.get("biosim.gcm.RNAP_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_VALUE", "30"); } if (biosimrc.get("biosim.gcm.RNAP_BINDING_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", ".033"); } if (biosimrc.get("biosim.gcm.STOICHIOMETRY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", "10"); } if (biosimrc.get("biosim.gcm.COOPERATIVITY_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", "2"); } if (biosimrc.get("biosim.gcm.ACTIVED_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.ACTIVED_VALUE", ".25"); } if (biosimrc.get("biosim.gcm.MAX_DIMER_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", "1"); } if (biosimrc.get("biosim.gcm.INITIAL_VALUE", "").equals("")) { biosimrc.put("biosim.gcm.INITIAL_VALUE", "0"); } if (biosimrc.get("biosim.sim.abs", "").equals("")) { biosimrc.put("biosim.sim.abs", "None"); } if (biosimrc.get("biosim.sim.type", "").equals("")) { biosimrc.put("biosim.sim.type", "ODE"); } if (biosimrc.get("biosim.sim.sim", "").equals("")) { biosimrc.put("biosim.sim.sim", "rkf45"); } if (biosimrc.get("biosim.sim.limit", "").equals("")) { biosimrc.put("biosim.sim.limit", "100.0"); } if (biosimrc.get("biosim.sim.useInterval", "").equals("")) { biosimrc.put("biosim.sim.useInterval", "Print Interval"); } if (biosimrc.get("biosim.sim.interval", "").equals("")) { biosimrc.put("biosim.sim.interval", "1.0"); } if (biosimrc.get("biosim.sim.step", "").equals("")) { biosimrc.put("biosim.sim.step", "inf"); } if (biosimrc.get("biosim.sim.error", "").equals("")) { biosimrc.put("biosim.sim.error", "1.0E-9"); } if (biosimrc.get("biosim.sim.seed", "").equals("")) { biosimrc.put("biosim.sim.seed", "314159"); } if (biosimrc.get("biosim.sim.runs", "").equals("")) { biosimrc.put("biosim.sim.runs", "1"); } if (biosimrc.get("biosim.sim.rapid1", "").equals("")) { biosimrc.put("biosim.sim.rapid1", "0.1"); } if (biosimrc.get("biosim.sim.rapid2", "").equals("")) { biosimrc.put("biosim.sim.rapid2", "0.1"); } if (biosimrc.get("biosim.sim.qssa", "").equals("")) { biosimrc.put("biosim.sim.qssa", "0.1"); } if (biosimrc.get("biosim.sim.concentration", "").equals("")) { biosimrc.put("biosim.sim.concentration", "15"); } if (biosimrc.get("biosim.learn.tn", "").equals("")) { biosimrc.put("biosim.learn.tn", "2"); } if (biosimrc.get("biosim.learn.tj", "").equals("")) { biosimrc.put("biosim.learn.tj", "2"); } if (biosimrc.get("biosim.learn.ti", "").equals("")) { biosimrc.put("biosim.learn.ti", "0.5"); } if (biosimrc.get("biosim.learn.bins", "").equals("")) { biosimrc.put("biosim.learn.bins", "4"); } if (biosimrc.get("biosim.learn.equaldata", "").equals("")) { biosimrc.put("biosim.learn.equaldata", "Equal Data Per Bins"); } if (biosimrc.get("biosim.learn.autolevels", "").equals("")) { biosimrc.put("biosim.learn.autolevels", "Auto"); } if (biosimrc.get("biosim.learn.ta", "").equals("")) { biosimrc.put("biosim.learn.ta", "1.15"); } if (biosimrc.get("biosim.learn.tr", "").equals("")) { biosimrc.put("biosim.learn.tr", "0.75"); } if (biosimrc.get("biosim.learn.tm", "").equals("")) { biosimrc.put("biosim.learn.tm", "0.0"); } if (biosimrc.get("biosim.learn.tt", "").equals("")) { biosimrc.put("biosim.learn.tt", "0.025"); } if (biosimrc.get("biosim.learn.debug", "").equals("")) { biosimrc.put("biosim.learn.debug", "0"); } if (biosimrc.get("biosim.learn.succpred", "").equals("")) { biosimrc.put("biosim.learn.succpred", "Successors"); } if (biosimrc.get("biosim.learn.findbaseprob", "").equals("")) { biosimrc.put("biosim.learn.findbaseprob", "False"); } // Open .biosimrc here // Packs the frame and displays it mainPanel = new JPanel(new BorderLayout()); tree = new FileTree(null, this, lema, atacs); log = new Log(); tab = new CloseAndMaxTabbedPane(false, this); tab.setPreferredSize(new Dimension(1100, 550)); tab.getPaneUI().addMouseListener(this); mainPanel.add(tree, "West"); mainPanel.add(tab, "Center"); mainPanel.add(log, "South"); mainPanel.add(toolbar, "North"); frame.setContentPane(mainPanel); frame.setJMenuBar(menuBar); frame.getGlassPane().setVisible(true); frame.getGlassPane().addMouseListener(this); frame.getGlassPane().addMouseMotionListener(this); frame.getGlassPane().addMouseWheelListener(this); frame.addMouseListener(this); menuBar.addMouseListener(this); frame.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; frame.setSize(frameSize); } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; frame.setSize(frameSize); } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; frame.setLocation(x, y); frame.setVisible(true); dispatcher = new KeyEventDispatcher() { public boolean dispatchKeyEvent(KeyEvent e) { if (e.getID() == KeyEvent.KEY_TYPED) { if (e.getKeyChar() == '') { if (tab.getTabCount() > 0) { KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(dispatcher); if (save(tab.getSelectedIndex()) != 0) { tab.remove(tab.getSelectedIndex()); } KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(dispatcher); } } } return false; } }; KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher); } public void preferences() { if (!async) { Undeclared = new JCheckBox("Check for undeclared units in SBML"); if (checkUndeclared) { Undeclared.setSelected(true); } else { Undeclared.setSelected(false); } Units = new JCheckBox("Check units in SBML"); if (checkUnits) { Units.setSelected(true); } else { Units.setSelected(false); } Preferences biosimrc = Preferences.userRoot(); JCheckBox dialog = new JCheckBox("Use File Dialog"); if (biosimrc.get("biosim.general.file_browser", "").equals("FileDialog")) { dialog.setSelected(true); } else { dialog.setSelected(false); } final JTextField ACTIVED_VALUE = new JTextField(biosimrc.get( "biosim.gcm.ACTIVED_VALUE", "")); final JTextField KACT_VALUE = new JTextField(biosimrc.get("biosim.gcm.KACT_VALUE", "")); final JTextField KBASAL_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBASAL_VALUE", "")); final JTextField KBIO_VALUE = new JTextField(biosimrc.get("biosim.gcm.KBIO_VALUE", "")); final JTextField KDECAY_VALUE = new JTextField(biosimrc.get("biosim.gcm.KDECAY_VALUE", "")); final JTextField COOPERATIVITY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.COOPERATIVITY_VALUE", "")); final JTextField KASSOCIATION_VALUE = new JTextField(biosimrc.get( "biosim.gcm.KASSOCIATION_VALUE", "")); final JTextField RNAP_VALUE = new JTextField(biosimrc.get("biosim.gcm.RNAP_VALUE", "")); final JTextField PROMOTER_COUNT_VALUE = new JTextField(biosimrc.get( "biosim.gcm.PROMOTER_COUNT_VALUE", "")); final JTextField INITIAL_VALUE = new JTextField(biosimrc.get( "biosim.gcm.INITIAL_VALUE", "")); final JTextField MAX_DIMER_VALUE = new JTextField(biosimrc.get( "biosim.gcm.MAX_DIMER_VALUE", "")); final JTextField OCR_VALUE = new JTextField(biosimrc.get("biosim.gcm.OCR_VALUE", "")); final JTextField RNAP_BINDING_VALUE = new JTextField(biosimrc.get( "biosim.gcm.RNAP_BINDING_VALUE", "")); final JTextField KREP_VALUE = new JTextField(biosimrc.get("biosim.gcm.KREP_VALUE", "")); final JTextField STOICHIOMETRY_VALUE = new JTextField(biosimrc.get( "biosim.gcm.STOICHIOMETRY_VALUE", "")); JPanel labels = new JPanel(new GridLayout(15, 1)); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.ACTIVED_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.ACTIVED_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KACT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KACT_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBASAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBASAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KBIO_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KBIO_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KDECAY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KDECAY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.COOPERATIVITY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.COOPERATIVITY_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.KASSOCIATION_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KASSOCIATION_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.RNAP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.PROMOTER_COUNT_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.PROMOTER_COUNT_STRING) + "):")); labels .add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.INITIAL_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.INITIAL_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.MAX_DIMER_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.MAX_DIMER_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.OCR_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.OCR_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.RNAP_BINDING_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.RNAP_BINDING_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer.getGuiName(GlobalConstants.KREP_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.KREP_STRING) + "):")); labels.add(new JLabel(CompatibilityFixer .getGuiName(GlobalConstants.STOICHIOMETRY_STRING) + " (" + CompatibilityFixer.getSBMLName(GlobalConstants.STOICHIOMETRY_STRING) + "):")); JPanel fields = new JPanel(new GridLayout(15, 1)); fields.add(ACTIVED_VALUE); fields.add(KACT_VALUE); fields.add(KBASAL_VALUE); fields.add(KBIO_VALUE); fields.add(KDECAY_VALUE); fields.add(COOPERATIVITY_VALUE); fields.add(KASSOCIATION_VALUE); fields.add(RNAP_VALUE); fields.add(PROMOTER_COUNT_VALUE); fields.add(INITIAL_VALUE); fields.add(MAX_DIMER_VALUE); fields.add(OCR_VALUE); fields.add(RNAP_BINDING_VALUE); fields.add(KREP_VALUE); fields.add(STOICHIOMETRY_VALUE); JPanel gcmPrefs = new JPanel(new GridLayout(1, 2)); gcmPrefs.add(labels); gcmPrefs.add(fields); String[] choices = { "None", "Abstraction", "Logical Abstraction" }; final JComboBox abs = new JComboBox(choices); abs.setSelectedItem(biosimrc.get("biosim.sim.abs", "")); if (abs.getSelectedItem().equals("None")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else if (abs.getSelectedItem().equals("Abstraction")) { choices = new String[] { "ODE", "Monte Carlo", "SBML", "Network", "Browser" }; } else { choices = new String[] { "Monte Carlo", "Markov", "SBML", "Network", "Browser" }; } final JComboBox type = new JComboBox(choices); type.setSelectedItem(biosimrc.get("biosim.sim.type", "")); if (type.getSelectedItem().equals("ODE")) { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } else if (type.getSelectedItem().equals("Monte Carlo")) { choices = new String[] { "gillespie", "emc-sim", "bunker", "nmc" }; } else if (type.getSelectedItem().equals("Markov")) { choices = new String[] { "atacs", "ctmc-transient" }; } else { choices = new String[] { "euler", "gear1", "gear2", "rk4imp", "rk8pd", "rkf45" }; } final JComboBox sim = new JComboBox(choices); sim.setSelectedItem(biosimrc.get("biosim.sim.sim", "")); abs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (abs.getSelectedItem().equals("None")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else if (abs.getSelectedItem().equals("Abstraction")) { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("ODE"); type.addItem("Monte Carlo"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } else { Object o = type.getSelectedItem(); type.removeAllItems(); type.addItem("Monte Carlo"); type.addItem("Markov"); type.addItem("SBML"); type.addItem("Network"); type.addItem("Browser"); type.setSelectedItem(o); } } }); type.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (type.getSelectedItem() == null) { } else if (type.getSelectedItem().equals("ODE")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Monte Carlo")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("gillespie"); sim.addItem("emc-sim"); sim.addItem("bunker"); sim.addItem("nmc"); sim.setSelectedItem(o); } else if (type.getSelectedItem().equals("Markov")) { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("atacs"); sim.addItem("ctmc-transient"); sim.setSelectedItem(o); } else { Object o = sim.getSelectedItem(); sim.removeAllItems(); sim.addItem("euler"); sim.addItem("gear1"); sim.addItem("gear2"); sim.addItem("rk4imp"); sim.addItem("rk8pd"); sim.addItem("rkf45"); sim.setSelectedIndex(5); sim.setSelectedItem(o); } } }); JTextField limit = new JTextField(biosimrc.get("biosim.sim.limit", "")); JTextField interval = new JTextField(biosimrc.get("biosim.sim.interval", "")); JTextField step = new JTextField(biosimrc.get("biosim.sim.step", "")); JTextField error = new JTextField(biosimrc.get("biosim.sim.error", "")); JTextField seed = new JTextField(biosimrc.get("biosim.sim.seed", "")); JTextField runs = new JTextField(biosimrc.get("biosim.sim.runs", "")); JTextField rapid1 = new JTextField(biosimrc.get("biosim.sim.rapid1", "")); JTextField rapid2 = new JTextField(biosimrc.get("biosim.sim.rapid2", "")); JTextField qssa = new JTextField(biosimrc.get("biosim.sim.qssa", "")); JTextField concentration = new JTextField(biosimrc.get("biosim.sim.concentration", "")); choices = new String[] { "Print Interval", "Number Of Steps" }; JComboBox useInterval = new JComboBox(choices); useInterval.setSelectedItem(biosimrc.get("biosim.sim.useInterval", "")); JPanel analysisLabels = new JPanel(new GridLayout(13, 1)); analysisLabels.add(new JLabel("Abstraction:")); analysisLabels.add(new JLabel("Simulation Type:")); analysisLabels.add(new JLabel("Possible Simulators/Analyzers:")); analysisLabels.add(new JLabel("Time Limit:")); analysisLabels.add(useInterval); analysisLabels.add(new JLabel("Maximum Time Step:")); analysisLabels.add(new JLabel("Absolute Error:")); analysisLabels.add(new JLabel("Random Seed:")); analysisLabels.add(new JLabel("Runs:")); analysisLabels.add(new JLabel("Rapid Equilibrium Condition 1:")); analysisLabels.add(new JLabel("Rapid Equilibrium Cojdition 2:")); analysisLabels.add(new JLabel("QSSA Condition:")); analysisLabels.add(new JLabel("Max Concentration Threshold:")); JPanel analysisFields = new JPanel(new GridLayout(13, 1)); analysisFields.add(abs); analysisFields.add(type); analysisFields.add(sim); analysisFields.add(limit); analysisFields.add(interval); analysisFields.add(step); analysisFields.add(error); analysisFields.add(seed); analysisFields.add(runs); analysisFields.add(rapid1); analysisFields.add(rapid2); analysisFields.add(qssa); analysisFields.add(concentration); JPanel analysisPrefs = new JPanel(new GridLayout(1, 2)); analysisPrefs.add(analysisLabels); analysisPrefs.add(analysisFields); final JTextField tn = new JTextField(biosimrc.get("biosim.learn.tn", "")); final JTextField tj = new JTextField(biosimrc.get("biosim.learn.tj", "")); final JTextField ti = new JTextField(biosimrc.get("biosim.learn.ti", "")); choices = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; final JComboBox bins = new JComboBox(choices); bins.setSelectedItem(biosimrc.get("biosim.learn.bins", "")); choices = new String[] { "Equal Data Per Bins", "Equal Spacing Of Bins" }; final JComboBox equaldata = new JComboBox(choices); equaldata.setSelectedItem(biosimrc.get("biosim.learn.equaldata", "")); choices = new String[] { "Auto", "User" }; final JComboBox autolevels = new JComboBox(choices); autolevels.setSelectedItem(biosimrc.get("biosim.learn.autolevels", "")); final JTextField ta = new JTextField(biosimrc.get("biosim.learn.ta", "")); final JTextField tr = new JTextField(biosimrc.get("biosim.learn.tr", "")); final JTextField tm = new JTextField(biosimrc.get("biosim.learn.tm", "")); final JTextField tt = new JTextField(biosimrc.get("biosim.learn.tt", "")); choices = new String[] { "0", "1", "2", "3" }; final JComboBox debug = new JComboBox(choices); debug.setSelectedItem(biosimrc.get("biosim.learn.debug", "")); choices = new String[] { "Successors", "Predecessors", "Both" }; final JComboBox succpred = new JComboBox(choices); succpred.setSelectedItem(biosimrc.get("biosim.learn.succpred", "")); choices = new String[] { "True", "False" }; final JComboBox findbaseprob = new JComboBox(choices); findbaseprob.setSelectedItem(biosimrc.get("biosim.learn.findbaseprob", "")); JPanel learnLabels = new JPanel(new GridLayout(13, 1)); learnLabels.add(new JLabel("Minimum Number Of Initial Vectors (Tn):")); learnLabels.add(new JLabel("Maximum Influence Vector Size (Tj):")); learnLabels.add(new JLabel("Score For Empty Influence Vector (Ti):")); learnLabels.add(new JLabel("Number Of Bins:")); learnLabels.add(new JLabel("Divide Bins:")); learnLabels.add(new JLabel("Generate Levels:")); learnLabels.add(new JLabel("Ratio For Activation (Ta):")); learnLabels.add(new JLabel("Ratio For Repression (Tr):")); learnLabels.add(new JLabel("Merge Influence Vectors Delta (Tm):")); learnLabels.add(new JLabel("Relax Thresholds Delta (Tt):")); learnLabels.add(new JLabel("Debug Level:")); learnLabels.add(new JLabel("Successors Or Predecessors:")); learnLabels.add(new JLabel("Basic FindBaseProb:")); JPanel learnFields = new JPanel(new GridLayout(13, 1)); learnFields.add(tn); learnFields.add(tj); learnFields.add(ti); learnFields.add(bins); learnFields.add(equaldata); learnFields.add(autolevels); learnFields.add(ta); learnFields.add(tr); learnFields.add(tm); learnFields.add(tt); learnFields.add(debug); learnFields.add(succpred); learnFields.add(findbaseprob); JPanel learnPrefs = new JPanel(new GridLayout(1, 2)); learnPrefs.add(learnLabels); learnPrefs.add(learnFields); JPanel generalPrefs = new JPanel(new BorderLayout()); generalPrefs.add(dialog, "North"); JPanel sbmlPrefsBordered = new JPanel(new BorderLayout()); JPanel sbmlPrefs = new JPanel(); sbmlPrefsBordered.add(Undeclared, "North"); sbmlPrefsBordered.add(Units, "Center"); sbmlPrefs.add(sbmlPrefsBordered); ((FlowLayout) sbmlPrefs.getLayout()).setAlignment(FlowLayout.LEFT); JTabbedPane prefTabs = new JTabbedPane(); prefTabs.addTab("General Preferences", dialog); prefTabs.addTab("SBML Preferences", sbmlPrefs); prefTabs.addTab("GCM Preferences", gcmPrefs); prefTabs.addTab("Analysis Preferences", analysisPrefs); prefTabs.addTab("Learn Preferences", learnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (dialog.isSelected()) { biosimrc.put("biosim.general.file_browser", "FileDialog"); } else { biosimrc.put("biosim.general.file_browser", "JFileChooser"); } if (Undeclared.isSelected()) { checkUndeclared = true; biosimrc.put("biosim.check.undeclared", "true"); } else { checkUndeclared = false; biosimrc.put("biosim.check.undeclared", "false"); } if (Units.isSelected()) { checkUnits = true; biosimrc.put("biosim.check.units", "true"); } else { checkUnits = false; biosimrc.put("biosim.check.units", "false"); } try { Double.parseDouble(KREP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KREP_VALUE", KREP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KACT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KACT_VALUE", KACT_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KBIO_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBIO_VALUE", KBIO_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(PROMOTER_COUNT_VALUE.getText().trim()); biosimrc.put("biosim.gcm.PROMOTER_COUNT_VALUE", PROMOTER_COUNT_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KASSOCIATION_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KASSOCIATION_VALUE", KASSOCIATION_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(KBASAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KBASAL_VALUE", KBASAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(OCR_VALUE.getText().trim()); biosimrc.put("biosim.gcm.OCR_VALUE", OCR_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(KDECAY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.KDECAY_VALUE", KDECAY_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_VALUE", RNAP_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(RNAP_BINDING_VALUE.getText().trim()); biosimrc.put("biosim.gcm.RNAP_BINDING_VALUE", RNAP_BINDING_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(STOICHIOMETRY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.STOICHIOMETRY_VALUE", STOICHIOMETRY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(COOPERATIVITY_VALUE.getText().trim()); biosimrc.put("biosim.gcm.COOPERATIVITY_VALUE", COOPERATIVITY_VALUE.getText() .trim()); } catch (Exception e1) { } try { Double.parseDouble(ACTIVED_VALUE.getText().trim()); biosimrc.put("biosim.gcm.ACTIVED_VALUE", ACTIVED_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(MAX_DIMER_VALUE.getText().trim()); biosimrc.put("biosim.gcm.MAX_DIMER_VALUE", MAX_DIMER_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(INITIAL_VALUE.getText().trim()); biosimrc.put("biosim.gcm.INITIAL_VALUE", INITIAL_VALUE.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(limit.getText().trim()); biosimrc.put("biosim.sim.limit", limit.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(interval.getText().trim()); biosimrc.put("biosim.sim.interval", interval.getText().trim()); } catch (Exception e1) { } try { if (step.getText().trim().equals("inf")) { biosimrc.put("biosim.sim.step", step.getText().trim()); } else { Double.parseDouble(step.getText().trim()); biosimrc.put("biosim.sim.step", step.getText().trim()); } } catch (Exception e1) { } try { Double.parseDouble(error.getText().trim()); biosimrc.put("biosim.sim.error", error.getText().trim()); } catch (Exception e1) { } try { Long.parseLong(seed.getText().trim()); biosimrc.put("biosim.sim.seed", seed.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(runs.getText().trim()); biosimrc.put("biosim.sim.runs", runs.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid1.getText().trim()); biosimrc.put("biosim.sim.rapid1", rapid1.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(rapid2.getText().trim()); biosimrc.put("biosim.sim.rapid2", rapid2.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(qssa.getText().trim()); biosimrc.put("biosim.sim.qssa", qssa.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(concentration.getText().trim()); biosimrc.put("biosim.sim.concentration", concentration.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.sim.useInterval", (String) useInterval.getSelectedItem()); biosimrc.put("biosim.sim.abs", (String) abs.getSelectedItem()); biosimrc.put("biosim.sim.type", (String) type.getSelectedItem()); biosimrc.put("biosim.sim.sim", (String) sim.getSelectedItem()); try { Integer.parseInt(tn.getText().trim()); biosimrc.put("biosim.learn.tn", tn.getText().trim()); } catch (Exception e1) { } try { Integer.parseInt(tj.getText().trim()); biosimrc.put("biosim.learn.tj", tj.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(ti.getText().trim()); biosimrc.put("biosim.learn.ti", ti.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.bins", (String) bins.getSelectedItem()); biosimrc.put("biosim.learn.equaldata", (String) equaldata.getSelectedItem()); biosimrc.put("biosim.learn.autolevels", (String) autolevels.getSelectedItem()); try { Double.parseDouble(ta.getText().trim()); biosimrc.put("biosim.learn.ta", ta.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tr.getText().trim()); biosimrc.put("biosim.learn.tr", tr.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tm.getText().trim()); biosimrc.put("biosim.learn.tm", tm.getText().trim()); } catch (Exception e1) { } try { Double.parseDouble(tt.getText().trim()); biosimrc.put("biosim.learn.tt", tt.getText().trim()); } catch (Exception e1) { } biosimrc.put("biosim.learn.debug", (String) debug.getSelectedItem()); biosimrc.put("biosim.learn.succpred", (String) succpred.getSelectedItem()); biosimrc.put("biosim.learn.findbaseprob", (String) findbaseprob.getSelectedItem()); for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).getGCM().loadDefaultParameters(); ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadParameters(); } } } else { } } else { JPanel prefPanel = new JPanel(new GridLayout(0, 2)); viewerLabel = new JLabel("External Editor for non-LHPN files:"); viewerField = new JTextField(""); viewerCheck = new JCheckBox("Use External Viewer"); viewerCheck.addActionListener(this); viewerCheck.setSelected(externView); viewerField.setText(viewer); viewerLabel.setEnabled(externView); viewerField.setEnabled(externView); prefPanel.add(viewerLabel); prefPanel.add(viewerField); prefPanel.add(viewerCheck); // Preferences biosimrc = Preferences.userRoot(); // JPanel vhdlPrefs = new JPanel(); // JPanel lhpnPrefs = new JPanel(); // JTabbedPane prefTabsNoLema = new JTabbedPane(); // prefTabsNoLema.addTab("VHDL Preferences", vhdlPrefs); // prefTabsNoLema.addTab("LHPN Preferences", lhpnPrefs); Object[] options = { "Save", "Cancel" }; int value = JOptionPane .showOptionDialog(frame, prefPanel, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { viewer = viewerField.getText(); } } } public void about() { final JFrame f = new JFrame("About"); // frame.setIconImage(new ImageIcon(System.getenv("BIOSIM") + // File.separator // + "gui" // + File.separator + "icons" + File.separator + // "iBioSim.png").getImage()); JLabel bioSim = new JLabel("iBioSim", JLabel.CENTER); Font font = bioSim.getFont(); font = font.deriveFont(Font.BOLD, 36.0f); bioSim.setFont(font); JLabel version = new JLabel("Version 1.02", JLabel.CENTER); JLabel uOfU = new JLabel("University of Utah", JLabel.CENTER); JButton credits = new JButton("Credits"); credits.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object[] options = { "Close" }; JOptionPane.showOptionDialog(f, "Nathan Barker\nKevin Jones\nHiroyuki Kuwahara\n" + "Curtis Madsen\nChris Myers\nNam Nguyen", "Credits", JOptionPane.YES_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); } }); JButton close = new JButton("Close"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel buttons = new JPanel(); buttons.add(credits); buttons.add(close); JPanel aboutPanel = new JPanel(new BorderLayout()); JPanel uOfUPanel = new JPanel(new BorderLayout()); uOfUPanel.add(bioSim, "North"); uOfUPanel.add(version, "Center"); uOfUPanel.add(uOfU, "South"); aboutPanel.add(new javax.swing.JLabel(new javax.swing.ImageIcon(System.getenv("BIOSIM") + File.separator + "gui" + File.separator + "icons" + File.separator + "iBioSim.png")), "North"); // aboutPanel.add(bioSim, "North"); aboutPanel.add(uOfUPanel, "Center"); aboutPanel.add(buttons, "South"); f.setContentPane(aboutPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } public void exit() { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } Preferences biosimrc = Preferences.userRoot(); for (int i = 0; i < numberRecentProj; i++) { biosimrc.put("biosim.recent.project." + i, recentProjects[i].getText()); biosimrc.put("biosim.recent.project.path." + i, recentProjectPaths[i]); } System.exit(1); } /** * This method performs different functions depending on what menu items are * selected. */ public void actionPerformed(ActionEvent e) { if (e.getSource() == viewerCheck) { externView = viewerCheck.isSelected(); viewerLabel.setEnabled(viewerCheck.isSelected()); viewerField.setEnabled(viewerCheck.isSelected()); } if (e.getSource() == viewCircuit) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLhpn(); } } else if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).viewLhpn(); } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewCircuit(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewCircuit(); } } } else if (e.getSource() == viewLog) { Component comp = tab.getSelectedComponent(); if (treeSelected) { try { if (new File(root + separator + "atacs.log").exists()) { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(frame(), "No log exists.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame(), "Unable to view log.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Verification) { ((Verification) array[0]).viewLog(); } else if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewLog(); } } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).viewLog(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).viewLog(); } } } else if (e.getSource() == saveParam) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Learn) { ((Learn) component).save(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); } else { ((Reb2Sac) ((JTabbedPane) comp).getComponentAt(2)).save(); } } } else if (e.getSource() == saveSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("SBML"); } else if (e.getSource() == saveTemp) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("template"); } else if (e.getSource() == saveAsGcm) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("GCM"); } else if (e.getSource() == saveAsLhpn) { Component comp = tab.getSelectedComponent(); ((LHPNEditor) comp).save(); } else if (e.getSource() == saveAsGraph) { Component comp = tab.getSelectedComponent(); ((Graph) comp).save(); } else if (e.getSource() == saveAsSbml) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML"); } else if (e.getSource() == saveAsTemplate) { Component comp = tab.getSelectedComponent(); ((GCM2SBMLEditor) comp).save("Save as SBML template"); } else if (e.getSource() == close && tab.getSelectedComponent() != null) { Component comp = tab.getSelectedComponent(); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), tab.getSelectedIndex()); } else if (e.getSource() == closeAll) { while (tab.getSelectedComponent() != null) { int index = tab.getSelectedIndex(); Component comp = tab.getComponent(index); Point point = comp.getLocation(); tab.fireCloseTabEvent(new MouseEvent(comp, e.getID(), e.getWhen(), e.getModifiers(), point.x, point.y, 0, false), index); } } else if (e.getSource() == viewRules) { Component comp = tab.getSelectedComponent(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).viewRules(); } else if (e.getSource() == viewTrace) { Component comp = tab.getSelectedComponent(); if (comp instanceof JPanel) { Component[] array = ((JPanel) comp).getComponents(); if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).viewTrace(); } else { ((Verification) array[0]).viewTrace(); } } } else if (e.getSource() == exportCsv) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(5); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(5); } } else if (e.getSource() == exportDat) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(6); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(); } } else if (e.getSource() == exportEps) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(3); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(3); } } else if (e.getSource() == exportJpg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(0); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(0); } } else if (e.getSource() == exportPdf) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(2); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(2); } } else if (e.getSource() == exportPng) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(1); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(1); } } else if (e.getSource() == exportSvg) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(4); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(4); } } else if (e.getSource() == exportTsd) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(7); } else if (comp instanceof JTabbedPane) { ((Graph) ((JTabbedPane) comp).getSelectedComponent()).export(7); } } else if (e.getSource() == about) { about(); } else if (e.getSource() == manual) { try { String directory = ""; String theFile = ""; if (!async) { theFile = "iBioSim.html"; } else if (atacs) { theFile = "ATACS.html"; } else { theFile = "LEMA.html"; } String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } File work = new File(directory); log.addText("Executing:\n" + command + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec(command + theFile, null, work); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to open manual.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the exit menu item is selected else if (e.getSource() == exit) { exit(); } // if the open popup menu is selected on a sim directory else if (e.getActionCommand().equals("openSim")) { openSim(); } else if (e.getActionCommand().equals("openLearn")) { if (lema) { openLearnLHPN(); } else { openLearn(); } } else if (e.getActionCommand().equals("openSynth")) { openSynth(); } else if (e.getActionCommand().equals("openVerification")) { openVerify(); } // if the create simulation popup menu is selected on a dot file else if (e.getActionCommand().equals("createSim")) { try { simulate(true); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the simulate popup menu is selected on an sbml file else if (e.getActionCommand().equals("simulate")) { try { simulate(false); } catch (Exception e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "You must select a valid sbml file for simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the synthesis popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createSynthesis")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String synthName = JOptionPane.showInputDialog(frame, "Enter Synthesis ID:", "Synthesis View ID", JOptionPane.PLAIN_MESSAGE); if (synthName != null && !synthName.trim().equals("")) { synthName = synthName.trim(); try { if (overwrite(root + separator + synthName, synthName)) { new File(root + separator + synthName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + synthName.trim() + ".syn")); out .write(("synthesis.file=" + circuitFileNoPath + "\n") .getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } try { FileInputStream in = new FileInputStream(new File(root + separator + circuitFileNoPath)); FileOutputStream out = new FileOutputStream(new File(root + separator + synthName.trim() + separator + circuitFileNoPath)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy circuit file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); String work = root + separator + synthName; String circuitFile = root + separator + synthName.trim() + separator + circuitFileNoPath; JPanel synthPane = new JPanel(); Synthesis synth = new Synthesis(work, circuitFile, log, this); // synth.addMouseListener(this); synthPane.add(synth); /* * JLabel noData = new JLabel("No data available"); * Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); * lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = * new JLabel("No data available"); font = * noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD * Graph", noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(synthName, synthPane, "Synthesis"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create Synthesis View directory.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the verify popup menu is selected on a vhdl or lhpn file else if (e.getActionCommand().equals("createVerify")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String verName = JOptionPane.showInputDialog(frame, "Enter Verification ID:", "Verification View ID", JOptionPane.PLAIN_MESSAGE); if (verName != null && !verName.trim().equals("")) { verName = verName.trim(); // try { if (overwrite(root + separator + verName, verName)) { new File(root + separator + verName).mkdir(); // new FileWriter(new File(root + separator + // synthName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String circuitFileNoPath = getFilename[getFilename.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + verName.trim() + separator + verName.trim() + ".ver")); out.write(("verification.file=" + circuitFileNoPath + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } /* * try { FileInputStream in = new FileInputStream(new * File(root + separator + circuitFileNoPath)); * FileOutputStream out = new FileOutputStream(new * File(root + separator + verName.trim() + separator + * circuitFileNoPath)); int read = in.read(); while * (read != -1) { out.write(read); read = in.read(); } * in.close(); out.close(); } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy * circuit file!", "Error Saving File", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); // String work = root + separator + verName; // log.addText(circuitFile); JPanel verPane = new JPanel(); Verification verify = new Verification(root + separator + verName, verName, circuitFileNoPath, log, this, lema, atacs); // verify.addMouseListener(this); verify.save(); verPane.add(verify); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(verName, verPane, "Verification"); } // } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Verification View directory.", "Error", // JOptionPane.ERROR_MESSAGE); // } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the delete popup menu is selected else if (e.getActionCommand().contains("delete") || e.getSource() == delete) { if (!tree.getFile().equals(root)) { if (new File(tree.getFile()).isDirectory()) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } File dir = new File(tree.getFile()); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } refreshTree(); } else { String[] views = canDelete(tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.remove(i); } } System.gc(); new File(tree.getFile()).delete(); refreshTree(); } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to delete the selected file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Delete File", JOptionPane.ERROR_MESSAGE); } } } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("createSBML")) { try { String[] dot = tree.getFile().split(separator); String sbmlFile = dot[dot.length - 1] .substring(0, dot[dot.length - 1].length() - 3) + "sbml"; // log.addText("Executing:\ngcm2sbml.pl " + tree.getFile() + " " // + root // + separator + sbmlFile // + "\n"); // Runtime exec = Runtime.getRuntime(); // String filename = tree.getFile(); // String directory = ""; // String theFile = ""; // if (filename.lastIndexOf('/') >= 0) { // directory = filename.substring(0, // filename.lastIndexOf('/') + 1); // theFile = filename.substring(filename.lastIndexOf('/') + 1); // } // if (filename.lastIndexOf('\\') >= 0) { // directory = filename.substring(0, filename // .lastIndexOf('\\') + 1); // theFile = filename // .substring(filename.lastIndexOf('\\') + 1); // } // File work = new File(directory); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + sbmlFile); refreshTree(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(sbmlFile)) { updateOpenSBML(sbmlFile); tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(root + separator + sbmlFile, null, log, this, null, null); addTab(sbmlFile, sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on a dot file else if (e.getActionCommand().equals("dotEditor")) { try { String directory = ""; String theFile = ""; String filename = tree.getFile(); if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { File work = new File(directory); GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open gcm file editor.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the edit popup menu is selected on an sbml file else if (e.getActionCommand().equals("sbmlEditor")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new SBML_Editor(tree.getFile(), null, log, this, null, null), "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph popup menu is selected on an sbml file else if (e.getActionCommand().equals("graph")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + directory + out + ".dot " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); Process graph = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); String error = ""; String output = ""; InputStream reb = graph.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = graph.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } graph.waitFor(); if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot\n"); exec.exec("dotty " + out + ".dot", null, work); } } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error graphing sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the browse popup menu is selected on an sbml file else if (e.getActionCommand().equals("browse")) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } Run run = new Run(null); JCheckBox dummy = new JCheckBox(); dummy.setSelected(false); run.createProperties(0, "Print Interval", 1, 1, 1, tree.getFile() .substring( 0, tree.getFile().length() - (tree.getFile().split(separator)[tree.getFile().split( separator).length - 1].length())), 314159, 1, new String[0], new String[0], "tsd.printer", "amount", tree.getFile() .split(separator), "none", frame, tree.getFile(), 0.1, 0.1, 0.1, 15, dummy, "", dummy, null); String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + directory + out + ".xhtml " + tree.getFile() + "\n"); Runtime exec = Runtime.getRuntime(); Process browse = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); String error = ""; String output = ""; InputStream reb = browse.getErrorStream(); int read = reb.read(); while (read != -1) { error += (char) read; read = reb.read(); } reb.close(); reb = browse.getInputStream(); read = reb.read(); while (read != -1) { output += (char) read; read = reb.read(); } reb.close(); if (!output.equals("")) { log.addText("Output:\n" + output + "\n"); } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } browse.waitFor(); String command = ""; if (error.equals("")) { if (System.getProperty("os.name").contentEquals("Linux")) { command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { command = "open "; } else { command = "cmd /c start "; } log.addText("Executing:\n" + command + directory + out + ".xhtml\n"); exec.exec(command + out + ".xhtml", null, work); } String remove; if (tree.getFile().substring(tree.getFile().length() - 4).equals("sbml")) { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + "properties"; } else { remove = tree.getFile().substring(0, tree.getFile().length() - 4) + ".properties"; } System.gc(); new File(remove).delete(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error viewing sbml file in a browser.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the graph dot popup menu is selected else if (e.getActionCommand().equals("graphDot")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("cp " + theFile + " " + theFile + ".dot", null, work); exec = Runtime.getRuntime(); exec.exec("open " + theFile + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + theFile + "\n"); Runtime exec = Runtime.getRuntime(); exec.exec("dotty " + theFile, null, work); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the save button is pressed on the Tool Bar else if (e.getActionCommand().equals("save")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { ((LHPNEditor) comp).save(); } else if (comp instanceof GCM2SBMLEditor) { ((GCM2SBMLEditor) comp).save("Save GCM"); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(false, "", true); } else if (comp instanceof Graph) { ((Graph) comp).save(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = ((JTabbedPane) comp).getSelectedIndex(); if (component instanceof Graph) { ((Graph) component).save(); } else if (component instanceof Learn) { ((Learn) component).saveGcm(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).saveLhpn(); } else if (component instanceof DataManager) { ((DataManager) component).saveChanges(((JTabbedPane) comp).getTitleAt(index)); } else if (component instanceof SBML_Editor) { ((SBML_Editor) component).save(false, "", true); } else if (component instanceof Reb2Sac) { ((Reb2Sac) component).save(); } } if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); } else if (comp.getName().equals("Synthesis")) { // ((Synthesis) tab.getSelectedComponent()).save(); Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); try { File output = new File(root + separator + fileName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + fileName); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + fileName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the save as button is pressed on the Tool Bar else if (e.getActionCommand().equals("saveas")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof LHPNEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter LHPN name:", "LHPN Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".g")) { newName = newName + ".g"; } ((LHPNEditor) comp).saveAs(newName); } else if (comp instanceof GCM2SBMLEditor) { String newName = JOptionPane.showInputDialog(frame(), "Enter GCM name:", "GCM Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (newName.contains(".gcm")) { newName = newName.replace(".gcm", ""); } ((GCM2SBMLEditor) comp).saveAs(newName); } else if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).saveAs(); } else if (comp instanceof Graph) { ((Graph) comp).saveAs(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).saveAs(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).saveAs(); } else if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).saveAs(); } } else if (comp instanceof JScrollPane) { String fileName = tab.getTitleAt(tab.getSelectedIndex()); String newName = ""; if (fileName.endsWith(".vhd")) { newName = JOptionPane.showInputDialog(frame(), "Enter VHDL name:", "VHDL Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".vhd")) { newName = newName + ".vhd"; } } else if (fileName.endsWith(".csp")) { newName = JOptionPane.showInputDialog(frame(), "Enter CSP name:", "CSP Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".csp")) { newName = newName + ".csp"; } } else if (fileName.endsWith(".hse")) { newName = JOptionPane.showInputDialog(frame(), "Enter HSE name:", "HSE Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".hse")) { newName = newName + ".hse"; } } else if (fileName.endsWith(".unc")) { newName = JOptionPane.showInputDialog(frame(), "Enter UNC name:", "UNC Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".unc")) { newName = newName + ".unc"; } } else if (fileName.endsWith(".rsg")) { newName = JOptionPane.showInputDialog(frame(), "Enter RSG name:", "RSG Name", JOptionPane.PLAIN_MESSAGE); if (newName == null) { return; } if (!newName.endsWith(".rsg")) { newName = newName + ".rsg"; } } try { File output = new File(root + separator + newName); output.createNewFile(); FileOutputStream outStream = new FileOutputStream(output); Component[] array = ((JScrollPane) comp).getComponents(); array = ((JViewport) array[0]).getComponents(); if (array[0] instanceof JTextArea) { String text = ((JTextArea) array[0]).getText(); char[] chars = text.toCharArray(); for (int j = 0; j < chars.length; j++) { outStream.write((int) chars[j]); } } outStream.close(); log.addText("Saving file:\n" + root + separator + newName); File oldFile = new File(root + separator + fileName); oldFile.delete(); tab.setTitleAt(tab.getSelectedIndex(), newName); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Error saving file " + newName, "Error", JOptionPane.ERROR_MESSAGE); } } } // if the run button is selected on the tool bar else if (e.getActionCommand().equals("run")) { Component comp = tab.getSelectedComponent(); // int index = tab.getSelectedIndex(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); int index = -1; for (int i = 0; i < ((JTabbedPane) comp).getTabCount(); i++) { if (((JTabbedPane) comp).getComponent(i) instanceof Reb2Sac) { index = i; break; } } if (component instanceof Graph) { if (index != -1) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton() .doClick(); } else { ((Graph) component).save(); ((Graph) component).run(); } } else if (component instanceof Learn) { ((Learn) component).save(); new Thread((Learn) component).start(); } else if (component instanceof LearnLHPN) { ((LearnLHPN) component).save(); ((LearnLHPN) component).learn(); } else if (component instanceof SBML_Editor) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof Reb2Sac) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JPanel) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } else if (component instanceof JScrollPane) { ((Reb2Sac) (((JTabbedPane) comp).getComponent(index))).getRunButton().doClick(); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { Component[] array = ((JPanel) comp).getComponents(); ((Verification) array[0]).save(); new Thread((Verification) array[0]).start(); } else if (comp.getName().equals("Synthesis")) { Component[] array = ((JPanel) comp).getComponents(); ((Synthesis) array[0]).save(); ((Synthesis) array[0]).run(); } } } else if (e.getActionCommand().equals("refresh")) { Component comp = tab.getSelectedComponent(); if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).refresh(); } } } else if (e.getActionCommand().equals("check")) { Component comp = tab.getSelectedComponent(); if (comp instanceof SBML_Editor) { ((SBML_Editor) comp).save(true, "", true); ((SBML_Editor) comp).check(); } } else if (e.getActionCommand().equals("export")) { Component comp = tab.getSelectedComponent(); if (comp instanceof Graph) { ((Graph) comp).export(); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); if (component instanceof Graph) { ((Graph) component).export(); } } } // if the new menu item is selected else if (e.getSource() == newProj) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } String filename = Buttons.browse(frame, null, null, JFileChooser.DIRECTORIES_ONLY, "New", -1); if (!filename.trim().equals("")) { filename = filename.trim(); File f = new File(filename); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(filename); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return; } } new File(filename).mkdir(); try { new FileWriter(new File(filename + separator + ".prj")).close(); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable create a new project.", "Error", JOptionPane.ERROR_MESSAGE); return; } root = filename; refresh(); tab.removeAll(); addRecentProject(filename); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } } // if the open project menu item is selected else if (e.getSource() == pref) { preferences(); } else if ((e.getSource() == openProj) || (e.getSource() == recentProjects[0]) || (e.getSource() == recentProjects[1]) || (e.getSource() == recentProjects[2]) || (e.getSource() == recentProjects[3]) || (e.getSource() == recentProjects[4])) { for (int i = 0; i < tab.getTabCount(); i++) { if (save(i) == 0) { return; } } File f; if (root == null) { f = null; } else { f = new File(root); } String projDir = ""; if (e.getSource() == openProj) { projDir = Buttons.browse(frame, f, null, JFileChooser.DIRECTORIES_ONLY, "Open", -1); } else if (e.getSource() == recentProjects[0]) { projDir = recentProjectPaths[0]; } else if (e.getSource() == recentProjects[1]) { projDir = recentProjectPaths[1]; } else if (e.getSource() == recentProjects[2]) { projDir = recentProjectPaths[2]; } else if (e.getSource() == recentProjects[3]) { projDir = recentProjectPaths[3]; } else if (e.getSource() == recentProjects[4]) { projDir = recentProjectPaths[4]; } if (!projDir.equals("")) { if (new File(projDir).isDirectory()) { boolean isProject = false; for (String temp : new File(projDir).list()) { if (temp.equals(".prj")) { isProject = true; } } if (isProject) { root = projDir; refresh(); tab.removeAll(); addRecentProject(projDir); importDot.setEnabled(true); importSbml.setEnabled(true); importVhdl.setEnabled(true); importLhpn.setEnabled(true); importCsp.setEnabled(true); importHse.setEnabled(true); importUnc.setEnabled(true); importRsg.setEnabled(true); importSpice.setEnabled(true); newCircuit.setEnabled(true); newModel.setEnabled(true); newVhdl.setEnabled(true); newLhpn.setEnabled(true); newCsp.setEnabled(true); newHse.setEnabled(true); newUnc.setEnabled(true); newRsg.setEnabled(true); newSpice.setEnabled(true); graph.setEnabled(true); probGraph.setEnabled(true); } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must select a valid project.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new circuit model menu item is selected else if (e.getSource() == newCircuit) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter GCM Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 4).equals(".gcm")) { simName += ".gcm"; } } else { simName += ".gcm"; } String modelID = ""; if (simName.length() > 3) { if (simName.substring(simName.length() - 4).equals(".gcm")) { modelID = simName.substring(0, simName.length() - 4); } else { modelID = simName.substring(0, simName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { File f = new File(root + separator + simName); f.createNewFile(); new GCMFile().save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, f .getName(), this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(f.getName(), gcm, "GCM Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new SBML model menu item is selected else if (e.getSource() == newModel) { if (root != null) { try { String simName = JOptionPane.showInputDialog(frame, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (simName.length() > 4) { if (!simName.substring(simName.length() - 5).equals(".sbml") && !simName.substring(simName.length() - 4).equals(".xml")) { simName += ".xml"; } } else { simName += ".xml"; } String modelID = ""; if (simName.length() > 4) { if (simName.substring(simName.length() - 5).equals(".sbml")) { modelID = simName.substring(0, simName.length() - 5); } else { modelID = simName.substring(0, simName.length() - 4); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + simName, simName)) { String f = new String(root + separator + simName); SBMLDocument document = new SBMLDocument(); document.createModel(); // document.setLevel(2); document.setLevelAndVersion(2, 3); Compartment c = document.getModel().createCompartment(); c.setId("default"); c.setSize(1.0); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + simName); SBML_Editor sbml = new SBML_Editor(f, null, log, this, null, null); // sbml.addMouseListener(this); addTab(f.split(separator)[f.split(separator).length - 1], sbml, "SBML Editor"); refreshTree(); } } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new vhdl menu item is selected else if (e.getSource() == newVhdl) { if (root != null) { try { String vhdlName = JOptionPane.showInputDialog(frame, "Enter VHDL Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (vhdlName != null && !vhdlName.trim().equals("")) { vhdlName = vhdlName.trim(); if (vhdlName.length() > 4) { if (!vhdlName.substring(vhdlName.length() - 5).equals(".vhd")) { vhdlName += ".vhd"; } } else { vhdlName += ".vhd"; } String modelID = ""; if (vhdlName.length() > 3) { if (vhdlName.substring(vhdlName.length() - 4).equals(".vhd")) { modelID = vhdlName.substring(0, vhdlName.length() - 4); } else { modelID = vhdlName.substring(0, vhdlName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + vhdlName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + vhdlName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(vhdlName, scroll, "VHDL Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } } // if the new lhpn menu item is selected else if (e.getSource() == newLhpn) { if (root != null) { try { String lhpnName = JOptionPane.showInputDialog(frame, "Enter LHPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 1) { if (!lhpnName.substring(lhpnName.length() - 2).equals(".g")) { lhpnName += ".g"; } } else { lhpnName += ".g"; } String modelID = ""; if (lhpnName.length() > 1) { if (lhpnName.substring(lhpnName.length() - 2).equals(".g")) { modelID = lhpnName.substring(0, lhpnName.length() - 2); } else { modelID = lhpnName.substring(0, lhpnName.length() - 1); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.delete(); f.createNewFile(); new LHPNFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } addTab(f.getName(), new LHPNEditor(root + separator, f.getName(), null, this, log), "LHPN Editor"); refreshTree(); } if (overwrite(root + separator + lhpnName, lhpnName)) { File f = new File(root + separator + lhpnName); f.createNewFile(); new LHPNFile(log).save(f.getAbsolutePath()); int i = getTab(f.getName()); if (i != -1) { tab.remove(i); } LHPNEditor lhpn = new LHPNEditor(root + separator, f.getName(), null, this, log); // lhpn.addMouseListener(this); addTab(f.getName(), lhpn, "LHPN Editor"); refreshTree(); } // File f = new File(root + separator + lhpnName); // f.createNewFile(); // String[] command = { "emacs", f.getName() }; // Runtime.getRuntime().exec(command); // refreshTree(); } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new csp menu item is selected else if (e.getSource() == newCsp) { if (root != null) { try { String cspName = JOptionPane.showInputDialog(frame, "Enter CSP Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (cspName != null && !cspName.trim().equals("")) { cspName = cspName.trim(); if (cspName.length() > 3) { if (!cspName.substring(cspName.length() - 4).equals(".csp")) { cspName += ".csp"; } } else { cspName += ".csp"; } String modelID = ""; if (cspName.length() > 3) { if (cspName.substring(cspName.length() - 4).equals(".csp")) { modelID = cspName.substring(0, cspName.length() - 4); } else { modelID = cspName.substring(0, cspName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + cspName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + cspName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(cspName, scroll, "CSP Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new hse menu item is selected else if (e.getSource() == newHse) { if (root != null) { try { String hseName = JOptionPane.showInputDialog(frame, "Enter Handshaking Expansion Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (hseName != null && !hseName.trim().equals("")) { hseName = hseName.trim(); if (hseName.length() > 3) { if (!hseName.substring(hseName.length() - 4).equals(".hse")) { hseName += ".hse"; } } else { hseName += ".hse"; } String modelID = ""; if (hseName.length() > 3) { if (hseName.substring(hseName.length() - 4).equals(".hse")) { modelID = hseName.substring(0, hseName.length() - 4); } else { modelID = hseName.substring(0, hseName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + hseName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + hseName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(hseName, scroll, "HSE Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new unc menu item is selected else if (e.getSource() == newUnc) { if (root != null) { try { String uncName = JOptionPane.showInputDialog(frame, "Enter Extended Burst Mode Machine ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (uncName != null && !uncName.trim().equals("")) { uncName = uncName.trim(); if (uncName.length() > 3) { if (!uncName.substring(uncName.length() - 4).equals(".unc")) { uncName += ".unc"; } } else { uncName += ".unc"; } String modelID = ""; if (uncName.length() > 3) { if (uncName.substring(uncName.length() - 4).equals(".unc")) { modelID = uncName.substring(0, uncName.length() - 4); } else { modelID = uncName.substring(0, uncName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + uncName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + uncName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(uncName, scroll, "UNC Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newRsg) { if (root != null) { try { String rsgName = JOptionPane.showInputDialog(frame, "Enter Reduced State Graph Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (rsgName != null && !rsgName.trim().equals("")) { rsgName = rsgName.trim(); if (rsgName.length() > 3) { if (!rsgName.substring(rsgName.length() - 4).equals(".rsg")) { rsgName += ".rsg"; } } else { rsgName += ".rsg"; } String modelID = ""; if (rsgName.length() > 3) { if (rsgName.substring(rsgName.length() - 4).equals(".rsg")) { modelID = rsgName.substring(0, rsgName.length() - 4); } else { modelID = rsgName.substring(0, rsgName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + rsgName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + rsgName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(rsgName, scroll, "RSG Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the new rsg menu item is selected else if (e.getSource() == newSpice) { if (root != null) { try { String spiceName = JOptionPane.showInputDialog(frame, "Enter Spice Circuit ID:", "Circuit ID", JOptionPane.PLAIN_MESSAGE); if (spiceName != null && !spiceName.trim().equals("")) { spiceName = spiceName.trim(); if (spiceName.length() > 3) { if (!spiceName.substring(spiceName.length() - 4).equals(".cir")) { spiceName += ".cir"; } } else { spiceName += ".cir"; } String modelID = ""; if (spiceName.length() > 3) { if (spiceName.substring(spiceName.length() - 4).equals(".cir")) { modelID = spiceName.substring(0, spiceName.length() - 4); } else { modelID = spiceName.substring(0, spiceName.length() - 3); } } if (!(IDpat.matcher(modelID).matches())) { JOptionPane .showMessageDialog( frame, "A model ID can only contain letters, numbers, and underscores.", "Invalid ID", JOptionPane.ERROR_MESSAGE); } else { File f = new File(root + separator + spiceName); f.createNewFile(); if (externView) { String command = viewerField.getText() + " " + root + separator + spiceName; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { JTextArea text = new JTextArea(""); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(spiceName, scroll, "Spice Editor"); } } } } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to create new model.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import sbml menu item is selected else if (e.getSource() == importSbml) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import SBML", -1); if (!filename.trim().equals("")) { if (new File(filename.trim()).isDirectory()) { JTextArea messageArea = new JTextArea(); messageArea.append("Imported SBML files contain the errors listed below. "); messageArea .append("It is recommended that you fix them before using these models or you may get unexpected results.\n\n"); boolean display = false; for (String s : new File(filename.trim()).list()) { try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim() + separator + s); if (document.getNumErrors() == 0) { if (overwrite(root + separator + s, s)) { long numErrors = document.checkConsistency(); if (numErrors > 0) { display = true; messageArea .append("--------------------------------------------------------------------------------------\n"); messageArea.append(s); messageArea .append("\n--------------------------------------------------------------------------------------\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // . // replace // ( // "." // , // ".\n" // ) // ; messageArea.append(i + ":" + error + "\n"); } } // FileOutputStream out = new // FileOutputStream(new File(root // + separator + s)); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + s); // String doc = // writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import files.", "Error", JOptionPane.ERROR_MESSAGE); } } refreshTree(); if (display) { final JFrame f = new JFrame("SBML Errors and Warnings"); messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } } else { String[] file = filename.trim().split(separator); try { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(filename.trim()); if (document.getNumErrors() > 0) { JOptionPane.showMessageDialog(frame, "Invalid SBML file.", "Error", JOptionPane.ERROR_MESSAGE); } else { if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { long numErrors = document.checkConsistency(); if (numErrors > 0) { final JFrame f = new JFrame("SBML Errors and Warnings"); JTextArea messageArea = new JTextArea(); messageArea .append("Imported SBML file contains the errors listed below. "); messageArea .append("It is recommended that you fix them before using this model or you may get unexpected results.\n\n"); for (long i = 0; i < numErrors; i++) { String error = document.getError(i).getMessage(); // . // replace // ( // "." // , // ".\n" // ) // ; messageArea.append(i + ":" + error + "\n"); } messageArea.setLineWrap(true); messageArea.setEditable(false); messageArea.setSelectionStart(0); messageArea.setSelectionEnd(0); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(600, 600)); scroll.setPreferredSize(new Dimension(600, 600)); scroll.setViewportView(messageArea); JButton close = new JButton("Dismiss"); close.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); JPanel consistencyPanel = new JPanel(new BorderLayout()); consistencyPanel.add(scroll, "Center"); consistencyPanel.add(close, "South"); f.setContentPane(consistencyPanel); f.pack(); Dimension screenSize; try { Toolkit tk = Toolkit.getDefaultToolkit(); screenSize = tk.getScreenSize(); } catch (AWTError awe) { screenSize = new Dimension(640, 480); } Dimension frameSize = f.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } int x = screenSize.width / 2 - frameSize.width / 2; int y = screenSize.height / 2 - frameSize.height / 2; f.setLocation(x, y); f.setVisible(true); } // FileOutputStream out = new // FileOutputStream(new File(root // + separator + file[file.length - 1])); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + file[file.length - 1]); // String doc = // writer.writeToString(document); // byte[] output = doc.getBytes(); // out.write(output); // out.close(); refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import dot menu item is selected else if (e.getSource() == importDot) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_AND_DIRECTORIES, "Import Genetic Circuit", -1); if (new File(filename.trim()).isDirectory()) { for (String s : new File(filename.trim()).list()) { if (!(filename.trim() + separator + s).equals("") && (filename.trim() + separator + s).length() > 3 && (filename.trim() + separator + s).substring( (filename.trim() + separator + s).length() - 4, (filename.trim() + separator + s).length()).equals(".gcm")) { try { // GCMParser parser = new GCMParser((filename.trim() + separator + s)); if (overwrite(root + separator + s, s)) { FileOutputStream out = new FileOutputStream(new File(root + separator + s)); FileInputStream in = new FileInputStream(new File((filename .trim() + separator + s))); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { if (filename.trim().length() > 3 && !filename.trim().substring(filename.trim().length() - 4, filename.trim().length()).equals(".gcm")) { JOptionPane.showMessageDialog(frame, "You must select a valid gcm file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.trim().equals("")) { String[] file = filename.trim().split(separator); try { // GCMParser parser = new GCMParser(filename.trim()); if (overwrite(root + separator + file[file.length - 1], file[file.length - 1])) { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename.trim())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import vhdl menu item is selected else if (e.getSource() == importVhdl) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import VHDL Model", -1); if (filename.length() > 3 && !filename.substring(filename.length() - 4, filename.length()).equals( ".vhd")) { JOptionPane.showMessageDialog(frame, "You must select a valid vhdl file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import lhpn menu item is selected else if (e.getSource() == importLhpn) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import LHPN", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 2, filename.length()).equals( ".g")) { JOptionPane.showMessageDialog(frame, "You must select a valid lhpn file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import csp menu item is selected else if (e.getSource() == importCsp) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import CSP", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".csp")) { JOptionPane.showMessageDialog(frame, "You must select a valid csp file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import hse menu item is selected else if (e.getSource() == importHse) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import HSE", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".hse")) { JOptionPane.showMessageDialog(frame, "You must select a valid handshaking expansion file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import unc menu item is selected else if (e.getSource() == importUnc) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import UNC", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".unc")) { JOptionPane.showMessageDialog(frame, "You must select a valid expanded burst mode machine file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import rsg menu item is selected else if (e.getSource() == importRsg) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import RSG", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".rsg")) { JOptionPane.showMessageDialog(frame, "You must select a valid rsg file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the import spice menu item is selected else if (e.getSource() == importSpice) { if (root != null) { String filename = Buttons.browse(frame, new File(root), null, JFileChooser.FILES_ONLY, "Import Spice Circuit", -1); if (filename.length() > 1 && !filename.substring(filename.length() - 4, filename.length()).equals( ".cir")) { JOptionPane.showMessageDialog(frame, "You must select a valid spice circuit file to import.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!filename.equals("")) { String[] file = filename.split(separator); try { FileOutputStream out = new FileOutputStream(new File(root + separator + file[file.length - 1])); FileInputStream in = new FileInputStream(new File(filename)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } // if the Graph data menu item is clicked else if (e.getSource() == graph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The TSD Graph:", "TSD Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".grf")) { graphName += ".grf"; } } else { graphName += ".grf"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName.trim(), true, false); addTab(graphName.trim(), g, "TSD Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == probGraph) { if (root != null) { String graphName = JOptionPane.showInputDialog(frame, "Enter A Name For The Probability Graph:", "Probability Graph Name", JOptionPane.PLAIN_MESSAGE); if (graphName != null && !graphName.trim().equals("")) { graphName = graphName.trim(); if (graphName.length() > 3) { if (!graphName.substring(graphName.length() - 4).equals(".prb")) { graphName += ".prb"; } } else { graphName += ".prb"; } if (overwrite(root + separator + graphName, graphName)) { Graph g = new Graph(null, "amount", graphName.trim().substring(0, graphName.length() - 4), "tsd.printer", root, "time", this, null, log, graphName.trim(), false, false); addTab(graphName.trim(), g, "Probability Graph"); g.save(); refreshTree(); } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("createLearn")) { if (root != null) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String lrnName = JOptionPane.showInputDialog(frame, "Enter Learn ID:", "Learn View ID", JOptionPane.PLAIN_MESSAGE); if (lrnName != null && !lrnName.trim().equals("")) { lrnName = lrnName.trim(); // try { if (overwrite(root + separator + lrnName, lrnName)) { new File(root + separator + lrnName).mkdir(); // new FileWriter(new File(root + separator + // lrnName + separator // + // ".lrn")).close(); String sbmlFile = tree.getFile(); String[] getFilename = sbmlFile.split(separator); String sbmlFileNoPath = getFilename[getFilename.length - 1]; if (sbmlFileNoPath.endsWith(".vhd")) { try { File work = new File(root); Runtime.getRuntime().exec("atacs -lvsl " + sbmlFileNoPath, null, work); sbmlFileNoPath = sbmlFileNoPath.replace(".vhd", ".g"); } catch (IOException e1) { JOptionPane.showMessageDialog(frame, "Unable to generate LHPN from VHDL file!", "Error Generating File", JOptionPane.ERROR_MESSAGE); } } try { FileOutputStream out = new FileOutputStream(new File(root + separator + lrnName.trim() + separator + lrnName.trim() + ".lrn")); if (lema) { out.write(("learn.file=" + sbmlFileNoPath + "\n").getBytes()); } else { out.write(("genenet.file=" + sbmlFileNoPath + "\n").getBytes()); } out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } refreshTree(); JTabbedPane lrnTab = new JTabbedPane(); DataManager data = new DataManager(root + separator + lrnName, this, lema); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "Data Manager"); if (lema) { LearnLHPN learn = new LearnLHPN(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } else { Learn learn = new Learn(root + separator + lrnName, log, this); lrnTab.addTab("Learn", learn); } // learn.addMouseListener(this); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph; tsdGraph = new Graph(null, "amount", lrnName + " data", "tsd.printer", root + separator + lrnName, "time", this, null, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName( "TSD Graph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); noData.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("Learn", * noData); lrnTab.getComponentAt(lrnTab.getComponents * ().length - 1).setName("Learn"); JLabel noData1 = new * JLabel("No data available"); font = * noData1.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); lrnTab.addTab("TSD Graph", * noData1); lrnTab.getComponentAt * (lrnTab.getComponents().length - 1).setName("TSD * Graph"); */ addTab(lrnName, lrnTab, null); } // } // catch (Exception e1) { // JOptionPane.showMessageDialog(frame, // "Unable to create Learn View directory.", "Error", // JOptionPane.ERROR_MESSAGE); // } } } else { JOptionPane.showMessageDialog(frame, "You must open or create a project first.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getActionCommand().equals("viewModel")) { try { if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String[] findTheFile = filename.split("\\."); String theFile = findTheFile[0] + ".dot"; File dot = new File(root + separator + theFile); dot.delete(); String cmd = "atacs -cPllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process ATACS = exec.exec(cmd, null, work); ATACS.waitFor(); log.addText("Executing:\n" + cmd); if (dot.exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + separator + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lvslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); String[] findTheFile = filename.split("\\."); view.waitFor(); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lcslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lhslllodpl " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lxodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { String filename = tree.getFile().split(separator)[tree.getFile().split( separator).length - 1]; String cmd = "atacs -lsodps " + filename; File work = new File(root); Runtime exec = Runtime.getRuntime(); Process view = exec.exec(cmd, null, work); log.addText("Executing:\n" + cmd); view.waitFor(); String[] findTheFile = filename.split("\\."); // String directory = ""; String theFile = findTheFile[0] + ".dot"; if (new File(root + separator + theFile).exists()) { String command = ""; if (System.getProperty("os.name").contentEquals("Linux")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "gnome-open "; } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { // directory = System.getenv("BIOSIM") + "/docs/"; command = "open "; } else { // directory = System.getenv("BIOSIM") + "\\docs\\"; command = "cmd /c start "; } log.addText(command + root + theFile + "\n"); exec.exec(command + theFile, null, work); } else { File log = new File(root + separator + "atacs.log"); BufferedReader input = new BufferedReader(new FileReader(log)); String line = null; JTextArea messageArea = new JTextArea(); while ((line = input.readLine()) != null) { messageArea.append(line); messageArea.append(System.getProperty("line.separator")); } input.close(); messageArea.setLineWrap(true); messageArea.setWrapStyleWord(true); messageArea.setEditable(false); JScrollPane scrolls = new JScrollPane(); scrolls.setMinimumSize(new Dimension(500, 500)); scrolls.setPreferredSize(new Dimension(500, 500)); scrolls.setViewportView(messageArea); JOptionPane.showMessageDialog(frame(), scrolls, "Log", JOptionPane.INFORMATION_MESSAGE); } } } catch (IOException e1) { e1.printStackTrace(); JOptionPane.showMessageDialog(frame, "File cannot be read", "Error", JOptionPane.ERROR_MESSAGE); } catch (InterruptedException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } else if (e.getActionCommand().equals("copy") || e.getSource() == copy) { if (!tree.getFile().equals(root)) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String copy = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } try { if (!copy.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (copy.length() > 4) { if (!copy.substring(copy.length() - 5).equals(".sbml") && !copy.substring(copy.length() - 4).equals(".xml")) { copy += ".xml"; } } else { copy += ".xml"; } if (copy.length() > 4) { if (copy.substring(copy.length() - 5).equals(".sbml")) { modelID = copy.substring(0, copy.length() - 5); } else { modelID = copy.substring(0, copy.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".gcm")) { copy += ".gcm"; } } else { copy += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".vhd")) { copy += ".vhd"; } } else { copy += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (copy.length() > 1) { if (!copy.substring(copy.length() - 2).equals(".g")) { copy += ".g"; } } else { copy += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".csp")) { copy += ".csp"; } } else { copy += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".hse")) { copy += ".hse"; } } else { copy += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".unc")) { copy += ".unc"; } } else { copy += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".rsg")) { copy += ".rsg"; } } else { copy += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".grf")) { copy += ".grf"; } } else { copy += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (copy.length() > 3) { if (!copy.substring(copy.length() - 4).equals(".prb")) { copy += ".prb"; } } else { copy += ".prb"; } } } if (copy .equals(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to copy file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + copy, copy)) { if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(tree.getFile()); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy); } else if ((tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse") || tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc") || tree.getFile().substring( tree.getFile().length() - 4).equals(".rsg")) || (tree.getFile().length() >= 2 && tree.getFile().substring( tree.getFile().length() - 2).equals(".g"))) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy)); FileInputStream in = new FileInputStream(new File(tree.getFile())); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else { boolean sim = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } } if (sim) { new File(root + separator + copy).mkdir(); // new FileWriter(new File(root + separator + // copy + // separator + // ".sim")).close(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile() + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + copy + separator + ss); } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + copy + separator + ss)); FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss .substring(ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".sim")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } else { new File(root + separator + copy).mkdir(); String[] s = new File(tree.getFile()).list(); for (String ss : s) { if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".tsd") || ss .substring(ss.length() - 4).equals(".lrn"))) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".lrn")) { out = new FileOutputStream(new File(root + separator + copy + separator + copy + ".lrn")); } else { out = new FileOutputStream(new File(root + separator + copy + separator + ss)); } FileInputStream in = new FileInputStream(new File(tree .getFile() + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); } } } } refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to copy file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("rename") || e.getSource() == rename) { if (!tree.getFile().equals(root)) { try { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } String modelID = null; String rename = JOptionPane.showInputDialog(frame, "Enter A New Filename:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } if (!rename.equals("")) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".xml")) { if (rename.length() > 4) { if (!rename.substring(rename.length() - 5).equals(".sbml") && !rename.substring(rename.length() - 4).equals(".xml")) { rename += ".xml"; } } else { rename += ".xml"; } if (rename.length() > 4) { if (rename.substring(rename.length() - 5).equals(".sbml")) { modelID = rename.substring(0, rename.length() - 5); } else { modelID = rename.substring(0, rename.length() - 4); } } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".gcm")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".gcm")) { rename += ".gcm"; } } else { rename += ".gcm"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".vhd")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".vhd")) { rename += ".vhd"; } } else { rename += ".vhd"; } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals( ".g")) { if (rename.length() > 1) { if (!rename.substring(rename.length() - 2).equals(".g")) { rename += ".g"; } } else { rename += ".g"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".csp")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".csp")) { rename += ".csp"; } } else { rename += ".csp"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".hse")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".hse")) { rename += ".hse"; } } else { rename += ".hse"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".unc")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".unc")) { rename += ".unc"; } } else { rename += ".unc"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".rsg")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".rsg")) { rename += ".rsg"; } } else { rename += ".rsg"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".grf")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".grf")) { rename += ".grf"; } } else { rename += ".grf"; } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals( ".prb")) { if (rename.length() > 3) { if (!rename.substring(rename.length() - 4).equals(".prb")) { rename += ".prb"; } } else { rename += ".prb"; } } if (rename.equals(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { JOptionPane.showMessageDialog(frame, "Unable to rename file." + "\nNew filename must be different than old filename.", "Error", JOptionPane.ERROR_MESSAGE); return; } if (overwrite(root + separator + rename, rename)) { if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".xml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".gcm") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".vhd") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".csp") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".hse") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".unc") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4) .equals(".rsg")) { String oldName = tree.getFile().split(separator)[tree.getFile() .split(separator).length - 1]; reassignViews(oldName, rename); } new File(tree.getFile()).renameTo(new File(root + separator + rename)); if (modelID != null) { SBMLReader reader = new SBMLReader(); SBMLDocument document = new SBMLDocument(); document = reader.readSBML(root + separator + rename); document.getModel().setId(modelID); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + rename); } if (rename.length() >= 5 && rename.substring(rename.length() - 5).equals(".sbml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".xml") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".gcm") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".vhd") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".csp") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".hse") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".unc") || rename.length() >= 4 && rename.substring(rename.length() - 4).equals(".rsg")) { updateViews(rename); } if (new File(root + separator + rename).isDirectory()) { if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".sim") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } else if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".pms") .renameTo(new File(root + separator + rename + separator + rename + ".sim")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".lrn") .renameTo(new File(root + separator + rename + separator + rename + ".lrn")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".grf") .renameTo(new File(root + separator + rename + separator + rename + ".grf")); } if (new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb").exists()) { new File(root + separator + rename + separator + tree.getFile().split(separator)[tree.getFile().split( separator).length - 1] + ".prb") .renameTo(new File(root + separator + rename + separator + rename + ".prb")); } } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { if (tree.getFile().length() > 4 && tree.getFile() .substring(tree.getFile().length() - 5).equals( ".sbml") || tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".xml")) { ((SBML_Editor) tab.getComponentAt(i)).setModelID(modelID); ((SBML_Editor) tab.getComponentAt(i)).setFile(root + separator + rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && (tree.getFile().substring( tree.getFile().length() - 4).equals(".grf") || tree .getFile().substring( tree.getFile().length() - 4).equals( ".prb"))) { ((Graph) tab.getComponentAt(i)).setGraphName(rename); tab.setTitleAt(i, rename); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".vhd")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 1 && tree.getFile() .substring(tree.getFile().length() - 2).equals( ".g")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 2)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".csp")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".hse")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".unc")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else if (tree.getFile().length() > 3 && tree.getFile() .substring(tree.getFile().length() - 4).equals( ".rsg")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reload(rename .substring(0, rename.length() - 4)); } else { JTabbedPane t = new JTabbedPane(); int selected = ((JTabbedPane) tab.getComponentAt(i)) .getSelectedIndex(); boolean analysis = false; ArrayList<Component> comps = new ArrayList<Component>(); for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)) .getTabCount(); j++) { Component c = ((JTabbedPane) tab.getComponentAt(i)) .getComponent(j); comps.add(c); } for (Component c : comps) { if (c instanceof Reb2Sac) { ((Reb2Sac) c).setSim(rename); analysis = true; } else if (c instanceof SBML_Editor) { String properties = root + separator + rename + separator + rename + ".sim"; new File(properties).renameTo(new File(properties .replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) c).isDirty(); ((SBML_Editor) c).setParamFileAndSimDir(properties, root + separator + rename); ((SBML_Editor) c).save(false, "", true); ((SBML_Editor) c).updateSBML(i, 0); ((SBML_Editor) c).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")) .renameTo(new File(properties)); } else if (c instanceof Graph) { // c.addMouseListener(this); Graph g = ((Graph) c); g.setDirectory(root + separator + rename); if (g.isTSDGraph()) { g.setGraphName(rename + ".grf"); } else { g.setGraphName(rename + ".prb"); } } else if (c instanceof Learn) { Learn l = ((Learn) c); l.setDirectory(root + separator + rename); } else if (c instanceof DataManager) { DataManager d = ((DataManager) c); d.setDirectory(root + separator + rename); } if (analysis) { if (c instanceof Reb2Sac) { t.addTab("Simulation Options", c); t.getComponentAt(t.getComponents().length - 1) .setName("Simulate"); } else if (c instanceof SBML_Editor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("SBML Editor"); } else if (c instanceof GCM2SBMLEditor) { t.addTab("Parameter Editor", c); t.getComponentAt(t.getComponents().length - 1) .setName("GCM Editor"); } else if (c instanceof Graph) { if (((Graph) c).isTSDGraph()) { t.addTab("TSD Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("TSD Graph"); } else { t.addTab("Probability Graph", c); t.getComponentAt( t.getComponents().length - 1) .setName("ProbGraph"); } } else { t.addTab("Abstraction Options", c); t.getComponentAt(t.getComponents().length - 1) .setName(""); } } } if (analysis) { t.setSelectedIndex(selected); tab.setComponentAt(i, t); } tab.setTitleAt(i, rename); tab.getComponentAt(i).setName(rename); } } } refreshTree(); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to rename selected file.", "Error", JOptionPane.ERROR_MESSAGE); } } } else if (e.getActionCommand().equals("openGraph")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] .contains(".grf")) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], true, false), "TSD Graph"); } else { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree .getFile().split(separator).length - 1], false, false), "Probability Graph"); } } } } public int getTab(String name) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { return i; } } return -1; } public void deleteDir(File dir) { int count = 0; do { File[] list = dir.listFiles(); System.gc(); for (int i = 0; i < list.length; i++) { if (list[i].isDirectory()) { deleteDir(list[i]); } else { list[i].delete(); } } count++; } while (!dir.delete() && count != 100); if (count == 100) { JOptionPane.showMessageDialog(frame, "Unable to delete.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * This method adds a new project to recent list */ public void addRecentProject(String projDir) { // boolean newOne = true; for (int i = 0; i < numberRecentProj; i++) { if (recentProjectPaths[i].equals(projDir)) { for (int j = 0; j <= i; j++) { String save = recentProjectPaths[j]; recentProjects[j] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } recentProjectPaths[j] = projDir; projDir = save; } for (int j = i + 1; j < numberRecentProj; j++) { if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[j], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[j]); } } return; } } if (numberRecentProj < 5) { numberRecentProj++; } for (int i = 0; i < numberRecentProj; i++) { String save = recentProjectPaths[i]; recentProjects[i] .setText(projDir.split(separator)[projDir.split(separator).length - 1]); if (file.getItem(file.getItemCount() - 1) == exit) { file.insert(recentProjects[i], file.getItemCount() - 3 - numberRecentProj); } else { file.add(recentProjects[i]); } recentProjectPaths[i] = projDir; projDir = save; } } /** * This method refreshes the menu. */ public void refresh() { mainPanel.remove(tree); tree = new FileTree(new File(root), this, lema, atacs); mainPanel.add(tree, "West"); mainPanel.validate(); } /** * This method refreshes the tree. */ public void refreshTree() { tree.fixTree(); mainPanel.validate(); updateGCM(); } /** * This method adds the given Component to a tab. */ public void addTab(String name, Component panel, String tabName) { tab.addTab(name, panel); // panel.addMouseListener(this); if (tabName != null) { tab.getComponentAt(tab.getTabCount() - 1).setName(tabName); } else { tab.getComponentAt(tab.getTabCount() - 1).setName(name); } tab.setSelectedIndex(tab.getTabCount() - 1); } /** * This method removes the given component from the tabs. */ public void removeTab(Component component) { tab.remove(component); } public JTabbedPane getTab() { return tab; } /** * Prompts the user to save work that has been done. */ public int save(int index) { if (tab.getComponentAt(index).getName().contains(("GCM")) || tab.getComponentAt(index).getName().contains("LHPN")) { if (tab.getComponentAt(index) instanceof GCM2SBMLEditor) { GCM2SBMLEditor editor = (GCM2SBMLEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save("gcm"); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } else if (tab.getComponentAt(index) instanceof LHPNEditor) { LHPNEditor editor = (LHPNEditor) tab.getComponentAt(index); if (editor.isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { editor.save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().equals("SBML Editor")) { if (tab.getComponentAt(index) instanceof SBML_Editor) { if (((SBML_Editor) tab.getComponentAt(index)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) tab.getComponentAt(index)).save(false, "", true); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else if (tab.getComponentAt(index).getName().contains("Graph")) { if (tab.getComponentAt(index) instanceof Graph) { if (((Graph) tab.getComponentAt(index)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save changes to " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Graph) tab.getComponentAt(index)).save(); return 1; } else if (value == JOptionPane.NO_OPTION) { return 1; } else { return 0; } } } return 1; } else { if (tab.getComponentAt(index) instanceof JTabbedPane) { for (int i = 0; i < ((JTabbedPane) tab.getComponentAt(index)).getTabCount(); i++) { if (((JTabbedPane) tab.getComponentAt(index)).getComponentAt(i).getName() .equals("Simulate")) { if (((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save simulation option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Reb2Sac) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("SBML Editor")) { if (((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).isDirty()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save parameter changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((SBML_Editor) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(false, "", true); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("Learn")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { if (((Learn) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Learn) { ((Learn) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { if (((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save learn option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof LearnLHPN) { ((LearnLHPN) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .equals("Data Manager")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof DataManager) { ((DataManager) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)).saveChanges(tab.getTitleAt(index)); } } else if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i).getName() .contains("Graph")) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { if (((Graph) ((JTabbedPane) tab.getComponentAt(index)).getComponent(i)) .hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save graph changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (((JTabbedPane) tab.getComponentAt(index)).getComponent(i) instanceof Graph) { Graph g = ((Graph) ((JTabbedPane) tab.getComponentAt(index)) .getComponent(i)); g.save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } } else if (tab.getComponentAt(index) instanceof JPanel) { if ((tab.getComponentAt(index)).getName().equals("Synthesis")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Synthesis) { if (((Synthesis) array[0]).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save synthesis option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (array[0] instanceof Synthesis) { ((Synthesis) array[0]).save(); } } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } else if (tab.getComponentAt(index).getName().equals("Verification")) { Component[] array = ((JPanel) tab.getComponentAt(index)).getComponents(); if (array[0] instanceof Verification) { if (((Verification) array[0]).hasChanged()) { Object[] options = { "Yes", "No", "Cancel" }; int value = JOptionPane.showOptionDialog(frame, "Do you want to save verification option changes for " + tab.getTitleAt(index) + "?", "Save Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { ((Verification) array[0]).save(); } else if (value == JOptionPane.CANCEL_OPTION) { return 0; } } } } } return 1; } } /** * Saves a circuit from a learn view to the project view */ public void saveGcm(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save genetic circuit.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Saves a circuit from a learn view to the project view */ public void saveLhpn(String filename, String path) { try { if (overwrite(root + separator + filename, filename)) { FileOutputStream out = new FileOutputStream(new File(root + separator + filename)); FileInputStream in = new FileInputStream(new File(path)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); refreshTree(); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save LHPN.", "Error", JOptionPane.ERROR_MESSAGE); } } /** * Returns the frame. */ public JFrame frame() { return frame; } public void mousePressed(MouseEvent e) { // log.addText(e.getSource().toString()); if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } else { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createVerification = new JMenuItem("Create Verification View"); createVerification.addActionListener(this); createVerification.setActionCommand("createVerify"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.add(createVerification); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem viewModel = new JMenuItem("View Model"); viewModel.addActionListener(this); viewModel.setActionCommand("viewModel"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(viewModel); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (tree.getFile() != null) { int index = tab.getSelectedIndex(); enableTabMenu(index); if (tree.getFile().length() >= 5 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { try { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { SBML_Editor sbml = new SBML_Editor(tree.getFile(), null, log, this, null, null); // sbml.addMouseListener(this); addTab(tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], sbml, "SBML Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "You must select a valid sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { GCM2SBMLEditor gcm = new GCM2SBMLEditor(work.getAbsolutePath(), theFile, this, log, false, null, null, null); // gcm.addMouseListener(this); addTab(theFile, gcm, "GCM Editor"); } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this gcm file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "VHDL Editor"); } } // String[] command = { "emacs", filename }; // Runtime.getRuntime().exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this vhdl file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 2 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } LHPNFile lhpn = new LHPNFile(log); if (new File(directory + theFile).length() > 0) { // log.addText("here"); lhpn.load(directory + theFile); // log.addText("there"); } // log.addText("load completed"); File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { // log.addText("make Editor"); LHPNEditor editor = new LHPNEditor(work.getAbsolutePath(), theFile, lhpn, this, log); // editor.addMouseListener(this); addTab(theFile, editor, "LHPN Editor"); // log.addText("Editor made"); } // String[] cmd = { "emacs", filename }; // Runtime.getRuntime().exec(cmd); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this lhpn file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "CSP Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this csp file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "HSE Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this hse file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "UNC Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this unc file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "RSG Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this rsg file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".cir")) { try { String filename = tree.getFile(); String directory = ""; String theFile = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); int i = getTab(theFile); if (i != -1) { tab.setSelectedIndex(i); } else { if (externView) { String command = viewerField.getText() + " " + directory + separator + theFile; Runtime exec = Runtime.getRuntime(); try { exec.exec(command); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to open external editor.", "Error Opening Editor", JOptionPane.ERROR_MESSAGE); } } else { File file = new File(work + separator + theFile); String input = ""; FileReader in = new FileReader(file); int read = in.read(); while (read != -1) { input += (char) read; read = in.read(); } in.close(); JTextArea text = new JTextArea(input); text.setEditable(true); text.setLineWrap(true); JScrollPane scroll = new JScrollPane(text); // gcm.addMouseListener(this); addTab(theFile, scroll, "Spice Editor"); } } } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to view this spice file.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], true, false), "TSD Graph"); } } else if (tree.getFile().length() >= 4 && tree.getFile().substring(tree.getFile().length() - 4).equals(".prb")) { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split( separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { addTab( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], new Graph(null, "amount", "title", "tsd.printer", root, "time", this, tree.getFile(), log, tree.getFile().split(separator)[tree.getFile().split( separator).length - 1], false, false), "Probability Graph"); } } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 3 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } if (sim) { openSim(); } else if (synth) { openSynth(); } else if (ver) { openVerify(); } else { if (lema) { openLearnLHPN(); } else { openLearn(); } } } } } } } public void mouseReleased(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities .convertPoint(glassPane, glassPanePoint, container); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); if (e != null) { deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e .getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e .getClickCount(), e.isPopupTrigger())); } if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } catch (Exception e1) { e1.printStackTrace(); } } } else { if (tree.getFile() != null) { if (e.isPopupTrigger() && tree.getFile() != null) { frame.getGlassPane().setVisible(false); popup.removeAll(); if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5) .equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("sbmlEditor"); JMenuItem graph = new JMenuItem("View Network"); graph.addActionListener(this); graph.setActionCommand("graph"); JMenuItem browse = new JMenuItem("View in Browser"); browse.addActionListener(this); browse.setActionCommand("browse"); JMenuItem simulate = new JMenuItem("Create Analysis View"); simulate.addActionListener(this); simulate.setActionCommand("simulate"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(simulate); popup.add(createLearn); popup.addSeparator(); popup.add(graph); popup.add(browse); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { JMenuItem create = new JMenuItem("Create Analysis View"); create.addActionListener(this); create.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem createSBML = new JMenuItem("Create SBML File"); createSBML.addActionListener(this); createSBML.setActionCommand("createSBML"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem graph = new JMenuItem("View Genetic Circuit"); graph.addActionListener(this); graph.setActionCommand("graphDot"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(create); popup.add(createLearn); popup.add(createSBML); popup.addSeparator(); popup.add(graph); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("openGraph"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem createAnalysis = new JMenuItem("Create Analysis View"); createAnalysis.addActionListener(this); createAnalysis.setActionCommand("createSim"); JMenuItem createLearn = new JMenuItem("Create Learn View"); createLearn.addActionListener(this); createLearn.setActionCommand("createLearn"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); if (atacs) { popup.add(createSynthesis); } // popup.add(createAnalysis); if (lema) { popup.add(createLearn); } popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { JMenuItem createSynthesis = new JMenuItem("Create Synthesis View"); createSynthesis.addActionListener(this); createSynthesis.setActionCommand("createSynthesis"); JMenuItem edit = new JMenuItem("View/Edit"); edit.addActionListener(this); edit.setActionCommand("dotEditor"); JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("delete"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(createSynthesis); popup.addSeparator(); popup.add(edit); popup.add(copy); popup.add(rename); popup.add(delete); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } } JMenuItem open; if (sim) { open = new JMenuItem("Open Analysis View"); open.addActionListener(this); open.setActionCommand("openSim"); } else if (synth) { open = new JMenuItem("Open Synthesis View"); open.addActionListener(this); open.setActionCommand("openSynth"); } else if (ver) { open = new JMenuItem("Open Verification View"); open.addActionListener(this); open.setActionCommand("openVerification"); } else { open = new JMenuItem("Open Learn View"); open.addActionListener(this); open.setActionCommand("openLearn"); } JMenuItem delete = new JMenuItem("Delete"); delete.addActionListener(this); delete.setActionCommand("deleteSim"); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(this); copy.setActionCommand("copy"); JMenuItem rename = new JMenuItem("Rename"); rename.addActionListener(this); rename.setActionCommand("rename"); popup.add(open); popup.addSeparator(); popup.add(copy); popup.add(rename); popup.add(delete); } if (popup.getComponentCount() != 0) { popup.show(e.getComponent(), e.getX(), e.getY()); } } else if (!popup.isVisible()) { frame.getGlassPane().setVisible(true); } } } } public void mouseMoved(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } } public void mouseWheelMoved(MouseWheelEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseWheelEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseWheelEvent(deepComponent, e.getID(), e.getWhen(), e.getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger(), e.getScrollType(), e.getScrollAmount(), e .getWheelRotation())); } } private void simulate(boolean isDot) throws Exception { if (isDot) { String simName = JOptionPane.showInputDialog(frame, "Enter Analysis ID:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String[] dot = tree.getFile().split(separator); String sbmlFile = /* * root + separator + simName + separator + */(dot[dot.length - 1].substring(0, dot[dot.length - 1] .length() - 3) + "sbml"); GCMParser parser = new GCMParser(tree.getFile()); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + simName + separator + sbmlFile); try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((dot[dot.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } // network.outputSBML(root + separator + sbmlFile); refreshTree(); sbmlFile = root + separator + simName + separator + (dot[dot.length - 1].substring(0, dot[dot.length - 1].length() - 3) + "sbml"); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFile, root, this, simName.trim(), log, simTab, null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (dot[dot.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, dot[dot.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } else { for (int i = 0; i < tab.getTabCount(); i++) { if (tab .getTitleAt(i) .equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(tree.getFile()); // document.setLevel(2); document.setLevelAndVersion(2, 3); String simName = JOptionPane.showInputDialog(frame, "Enter analysis id:", "Analysis ID", JOptionPane.PLAIN_MESSAGE); if (simName != null && !simName.trim().equals("")) { simName = simName.trim(); if (overwrite(root + separator + simName, simName)) { new File(root + separator + simName).mkdir(); // new FileWriter(new File(root + separator + simName + // separator + // ".sim")).close(); String sbmlFile = tree.getFile(); String[] sbml1 = tree.getFile().split(separator); String sbmlFileProp = root + separator + simName + separator + sbml1[sbml1.length - 1]; try { FileOutputStream out = new FileOutputStream(new File(root + separator + simName.trim() + separator + simName.trim() + ".sim")); out.write((sbml1[sbml1.length - 1] + "\n").getBytes()); out.close(); } catch (Exception e1) { JOptionPane.showMessageDialog(frame, "Unable to save parameter file!", "Error Saving File", JOptionPane.ERROR_MESSAGE); } new FileOutputStream(new File(sbmlFileProp)).close(); /* * try { FileOutputStream out = new FileOutputStream(new * File(sbmlFile)); SBMLWriter writer = new SBMLWriter(); * String doc = writer.writeToString(document); byte[] * output = doc.getBytes(); out.write(output); out.close(); * } catch (Exception e1) { * JOptionPane.showMessageDialog(frame, "Unable to copy sbml * file to output location.", "Error", * JOptionPane.ERROR_MESSAGE); } */ refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlFile, sbmlFileProp, root, this, simName .trim(), log, simTab, null); // reb2sac.addMouseListener(this); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); JPanel abstraction = reb2sac.getAdvanced(); // abstraction.addMouseListener(this); simTab.addTab("Abstraction Options", abstraction); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (sbml1[sbml1.length - 1].contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, sbml1[sbml1.length - 1], this, log, true, simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlFile, reb2sac, log, this, root + separator + simName.trim(), root + separator + simName.trim() + separator + simName.trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font * font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No * data available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ addTab(simName, simTab, null); } } } } private void openLearn() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); Learn learn = new Learn(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, true); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); // } /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openLearnLHPN() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JTabbedPane lrnTab = new JTabbedPane(); // String graphFile = ""; String open = null; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } else if (end.equals(".grf")) { open = tree.getFile() + separator + list[i]; } } } } String lrnFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".lrn"; String lrnFile2 = tree.getFile() + separator + ".lrn"; Properties load = new Properties(); String learnFile = ""; try { if (new File(lrnFile2).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile2)); load.load(in); in.close(); new File(lrnFile2).delete(); } if (new File(lrnFile).exists()) { FileInputStream in = new FileInputStream(new File(lrnFile)); load.load(in); in.close(); if (load.containsKey("genenet.file")) { learnFile = load.getProperty("genenet.file"); learnFile = learnFile.split(separator)[learnFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(lrnFile)); load.store(out, learnFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + learnFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + learnFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { DataManager data = new DataManager(tree.getFile(), this, lema); // data.addMouseListener(this); lrnTab.addTab("Data Manager", data); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Data Manager"); LearnLHPN learn = new LearnLHPN(tree.getFile(), log, this); // learn.addMouseListener(this); lrnTab.addTab("Learn", learn); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("Learn"); Graph tsdGraph = new Graph(null, "amount", tree.getFile().split(separator)[tree .getFile().split(separator).length - 1] + " data", "tsd.printer", tree.getFile(), "time", this, open, log, null, true, false); // tsdGraph.addMouseListener(this); lrnTab.addTab("TSD Graph", tsdGraph); lrnTab.getComponentAt(lrnTab.getComponents().length - 1).setName("TSD Graph"); // } /* * else { lrnTab.addTab("Data Manager", new * DataManager(tree.getFile(), this)); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Data Manager"); JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("Learn", noData); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("Learn"); JLabel noData1 = new JLabel("No data * available"); font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * lrnTab.addTab("TSD Graph", noData1); * lrnTab.getComponentAt(lrnTab.getComponents().length - * 1).setName("TSD Graph"); } */ addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], lrnTab, null); } } private void openSynth() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel synthPanel = new JPanel(); // String graphFile = ""; if (new File(tree.getFile()).isDirectory()) { String[] list = new File(tree.getFile()).list(); int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = tree.getFile() + separator + // list[i]; } } } } } } String synthFile = tree.getFile() + separator + tree.getFile().split(separator)[tree.getFile().split(separator).length - 1] + ".syn"; String synthFile2 = tree.getFile() + separator + ".syn"; Properties load = new Properties(); String synthesisFile = ""; try { if (new File(synthFile2).exists()) { FileInputStream in = new FileInputStream(new File(synthFile2)); load.load(in); in.close(); new File(synthFile2).delete(); } if (new File(synthFile).exists()) { FileInputStream in = new FileInputStream(new File(synthFile)); load.load(in); in.close(); if (load.containsKey("synthesis.file")) { synthesisFile = load.getProperty("synthesis.file"); synthesisFile = synthesisFile.split(separator)[synthesisFile .split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(synthesisFile)); load.store(out, synthesisFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(synthesisFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(root + separator + synthesisFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + synthesisFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Synthesis synth = new Synthesis(tree.getFile(), "flag", log, this); // synth.addMouseListener(this); synthPanel.add(synth); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], synthPanel, "Synthesis"); } } private void openVerify() { boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( tree.getFile().split(separator)[tree.getFile().split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { JPanel verPanel = new JPanel(); // String graphFile = ""; /* * if (new File(tree.getFile()).isDirectory()) { String[] list = new * File(tree.getFile()).list(); int run = 0; for (int i = 0; i < * list.length; i++) { if (!(new File(list[i]).isDirectory()) && * list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; * j++) { end = list[i].charAt(list[i].length() - j) + end; } if * (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) * { if (list[i].contains("run-")) { int tempNum = * Integer.parseInt(list[i].substring(4, list[i] .length() - * end.length())); if (tempNum > run) { run = tempNum; // graphFile * = tree.getFile() + separator + // list[i]; } } } } } } */ String verName = tree.getFile().split(separator)[tree.getFile().split(separator).length - 1]; String verFile = tree.getFile() + separator + verName + ".ver"; Properties load = new Properties(); String verifyFile = ""; try { if (new File(verFile).exists()) { FileInputStream in = new FileInputStream(new File(verFile)); load.load(in); in.close(); if (load.containsKey("verification.file")) { verifyFile = load.getProperty("verification.file"); verifyFile = verifyFile.split(separator)[verifyFile.split(separator).length - 1]; } } FileOutputStream out = new FileOutputStream(new File(verifyFile)); load.store(out, verifyFile); out.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame(), "Unable to load properties file!", "Error Loading Properties", JOptionPane.ERROR_MESSAGE); } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(verifyFile)) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } if (!(new File(verFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + verifyFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } // if (!graphFile.equals("")) { Verification ver = new Verification(root + separator + verName, verName, "flag", log, this, lema, atacs); // ver.addMouseListener(this); verPanel.add(ver); addTab(tree.getFile().split(separator)[tree.getFile().split(separator).length - 1], verPanel, "Verification"); } } private void openSim() { String filename = tree.getFile(); boolean done = false; for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals( filename.split(separator)[filename.split(separator).length - 1])) { tab.setSelectedIndex(i); done = true; } } if (!done) { if (filename != null && !filename.equals("")) { if (new File(filename).isDirectory()) { if (new File(filename + separator + ".sim").exists()) { new File(filename + separator + ".sim").delete(); } String[] list = new File(filename).list(); String getAFile = ""; // String probFile = ""; String openFile = ""; // String graphFile = ""; String open = null; String openProb = null; int run = 0; for (int i = 0; i < list.length; i++) { if (!(new File(list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals("sbml")) { getAFile = filename + separator + list[i]; } else if (end.equals(".xml") && getAFile.equals("")) { getAFile = filename + separator + list[i]; } else if (end.equals(".txt") && list[i].contains("sim-rep")) { // probFile = filename + separator + list[i]; } else if (end.equals("ties") && list[i].contains("properties") && !(list[i].equals("species.properties"))) { openFile = filename + separator + list[i]; } else if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv") || end.contains("=")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; // graphFile = filename + separator + // list[i]; } } else if (list[i].contains("euler-run.") || list[i].contains("gear1-run.") || list[i].contains("gear2-run.") || list[i].contains("rk4imp-run.") || list[i].contains("rk8pd-run.") || list[i].contains("rkf45-run.")) { // graphFile = filename + separator + // list[i]; } else if (end.contains("=")) { // graphFile = filename + separator + // list[i]; } } else if (end.equals(".grf")) { open = filename + separator + list[i]; } else if (end.equals(".prb")) { openProb = filename + separator + list[i]; } } else if (new File(filename + separator + list[i]).isDirectory()) { String[] s = new File(filename + separator + list[i]).list(); for (int j = 0; j < s.length; j++) { if (s[j].contains("sim-rep")) { // probFile = filename + separator + list[i] // + separator + // s[j]; } else if (s[j].contains(".tsd")) { // graphFile = filename + separator + // list[i] + separator + // s[j]; } } } } if (!getAFile.equals("")) { String[] split = filename.split(separator); String simFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"; String pmsFile = root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".pms"; if (new File(pmsFile).exists()) { if (new File(simFile).exists()) { new File(pmsFile).delete(); } else { new File(pmsFile).renameTo(new File(simFile)); } } String sbmlLoadFile = ""; String gcmFile = ""; if (new File(simFile).exists()) { try { Scanner s = new Scanner(new File(simFile)); if (s.hasNextLine()) { sbmlLoadFile = s.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; if (sbmlLoadFile.equals("")) { JOptionPane .showMessageDialog( frame, "Unable to open view because " + "the sbml linked to this view is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } else if (!(new File(root + separator + sbmlLoadFile).exists())) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + split[split.length - 1].trim() + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (s.hasNextLine()) { s.nextLine(); } s.close(); File f = new File(sbmlLoadFile); if (!f.exists()) { sbmlLoadFile = root + separator + f.getName(); } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); return; } } else { sbmlLoadFile = root + separator + getAFile.split(separator)[getAFile.split(separator).length - 1]; if (!new File(sbmlLoadFile).exists()) { sbmlLoadFile = getAFile; /* * JOptionPane.showMessageDialog(frame, "Unable * to load sbml file.", "Error", * JOptionPane.ERROR_MESSAGE); return; */ } } if (!new File(sbmlLoadFile).exists()) { JOptionPane.showMessageDialog(frame, "Unable to open view because " + sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1] + " is missing.", "Error", JOptionPane.ERROR_MESSAGE); return; } for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i) .equals( sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1])) { tab.setSelectedIndex(i); if (save(i) != 1) { return; } break; } } JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, getAFile, root, this, split[split.length - 1].trim(), log, simTab, openFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1) .setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", // reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + split[split.length - 1].trim(), root + separator + split[split.length - 1].trim() + separator + split[split.length - 1].trim() + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } // if (open != null) { Graph tsdGraph = reb2sac.createGraph(open); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "TSD Graph"); /* * } else if (!graphFile.equals("")) { * simTab.addTab("TSD Graph", * reb2sac.createGraph(open)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } / else { JLabel noData = * new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, * 42.0f); noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); } */ // if (openProb != null) { Graph probGraph = reb2sac.createProbGraph(openProb); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName( "ProbGraph"); /* * } else if (!probFile.equals("")) { * simTab.addTab("Probability Graph", * reb2sac.createProbGraph(openProb)); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } else { JLabel noData1 = * new JLabel("No data available"); Font font1 = * noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font1); * noData1.setHorizontalAlignment * (SwingConstants.CENTER); simTab.addTab("Probability * Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); } */ addTab(split[split.length - 1], simTab, null); } } } } } private class NewAction extends AbstractAction { NewAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(newProj); if (!async) { popup.add(newCircuit); popup.add(newModel); } else if (atacs) { popup.add(newVhdl); popup.add(newLhpn); popup.add(newCsp); popup.add(newHse); popup.add(newUnc); popup.add(newRsg); } else { popup.add(newVhdl); popup.add(newLhpn); popup.add(newSpice); } popup.add(graph); popup.add(probGraph); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class SaveAction extends AbstractAction { SaveAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(saveAsGcm); } else { popup.add(saveAsLhpn); } popup.add(saveAsGraph); if (!lema) { popup.add(saveAsSbml); popup.add(saveAsTemplate); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ImportAction extends AbstractAction { ImportAction() { super(); } public void actionPerformed(ActionEvent e) { if (!lema) { popup.add(importDot); popup.add(importSbml); } else if (atacs) { popup.add(importVhdl); popup.add(importLhpn); popup.add(importCsp); popup.add(importHse); popup.add(importUnc); popup.add(importRsg); } else { popup.add(importVhdl); popup.add(importLhpn); popup.add(importSpice); } if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ExportAction extends AbstractAction { ExportAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(exportCsv); popup.add(exportDat); popup.add(exportEps); popup.add(exportJpg); popup.add(exportPdf); popup.add(exportPng); popup.add(exportSvg); popup.add(exportTsd); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } private class ModelAction extends AbstractAction { ModelAction() { super(); } public void actionPerformed(ActionEvent e) { popup.add(viewModGraph); popup.add(viewModBrowser); if (popup.getComponentCount() != 0) { popup.show(mainPanel, mainPanel.getMousePosition().x, mainPanel.getMousePosition().y); } } } public void mouseClicked(MouseEvent e) { if (e.getSource() == frame.getGlassPane()) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e.isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); if ((deepComponent instanceof JTree) && (e.getClickCount() != 2)) { enableTreeMenu(); } else { enableTabMenu(tab.getSelectedIndex()); } } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseDragged(MouseEvent e) { Component glassPane = frame.getGlassPane(); Point glassPanePoint = e.getPoint(); // Component component = e.getComponent(); Container container = frame.getContentPane(); Point containerPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, frame .getContentPane()); if (containerPoint.y < 0) { // we're not in the content pane if (containerPoint.y + menuBar.getHeight() >= 0) { Component component = menuBar.getComponentAt(glassPanePoint); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, component); component.dispatchEvent(new MouseEvent(component, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); frame.getGlassPane().setVisible(false); } } else { try { Component deepComponent = SwingUtilities.getDeepestComponentAt(container, containerPoint.x, containerPoint.y); Point componentPoint = SwingUtilities.convertPoint(glassPane, glassPanePoint, deepComponent); // if (deepComponent instanceof ScrollableTabPanel) { // deepComponent = tab.findComponentAt(componentPoint); // } deepComponent.dispatchEvent(new MouseEvent(deepComponent, e.getID(), e.getWhen(), e .getModifiers(), componentPoint.x, componentPoint.y, e.getClickCount(), e .isPopupTrigger())); } catch (Exception e1) { } } } public JMenuItem getExitButton() { return exit; } /** * This is the main method. It excecutes the BioSim GUI FrontEnd program. */ public static void main(String args[]) { String varname; if (System.getProperty("mrj.version") != null) varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. else varname = "LD_LIBRARY_PATH"; // We're not on a Mac. try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error: could not link with the libSBML library." + " It is likely\nyour " + varname + " environment variable does not include\nthe" + " directory containing the libsbml library file."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println("Error: unable to load the file libsbmlj.jar." + " It is likely\nyour " + varname + " environment" + " variable or CLASSPATH variable\ndoes not include" + " the directory containing the libsbmlj.jar file."); System.exit(1); } catch (SecurityException e) { System.err.println("Could not load the libSBML library files due to a" + " security exception."); System.exit(1); } boolean lemaFlag = false, atacsFlag = false; if (args.length > 0) { for (int i = 0; i < args.length; i++) { if (args[i].equals("-lema")) { lemaFlag = true; } else if (args[i].equals("-atacs")) { atacsFlag = true; } } } new BioSim(lemaFlag, atacsFlag); } public void copySim(String newSim) { try { new File(root + separator + newSim).mkdir(); // new FileWriter(new File(root + separator + newSim + separator + // ".sim")).close(); String oldSim = tab.getTitleAt(tab.getSelectedIndex()); String[] s = new File(root + separator + oldSim).list(); String sbmlFile = ""; String propertiesFile = ""; String sbmlLoadFile = null; String gcmFile = null; for (String ss : s) { if (ss.length() > 4 && ss.substring(ss.length() - 5).equals(".sbml") || ss.length() > 3 && ss.substring(ss.length() - 4).equals(".xml")) { SBMLReader reader = new SBMLReader(); SBMLDocument document = reader.readSBML(root + separator + oldSim + separator + ss); SBMLWriter writer = new SBMLWriter(); writer.writeSBML(document, root + separator + newSim + separator + ss); sbmlFile = root + separator + newSim + separator + ss; } else if (ss.length() > 10 && ss.substring(ss.length() - 11).equals(".properties")) { FileOutputStream out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); propertiesFile = root + separator + newSim + separator + ss; } else if (ss.length() > 3 && (ss.substring(ss.length() - 4).equals(".dat") || ss.substring(ss.length() - 4).equals(".sad") || ss.substring(ss.length() - 4).equals(".pms") || ss.substring( ss.length() - 4).equals(".sim")) && !ss.equals(".sim")) { FileOutputStream out; if (ss.substring(ss.length() - 4).equals(".pms")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else if (ss.substring(ss.length() - 4).equals(".sim")) { out = new FileOutputStream(new File(root + separator + newSim + separator + newSim + ".sim")); } else { out = new FileOutputStream(new File(root + separator + newSim + separator + ss)); } FileInputStream in = new FileInputStream(new File(root + separator + oldSim + separator + ss)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); if (ss.substring(ss.length() - 4).equals(".pms")) { if (new File(root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim").exists()) { new File(root + separator + newSim + separator + ss).delete(); } else { new File(root + separator + newSim + separator + ss).renameTo(new File( root + separator + newSim + separator + ss.substring(0, ss.length() - 4) + ".sim")); } ss = ss.substring(0, ss.length() - 4) + ".sim"; } if (ss.substring(ss.length() - 4).equals(".sim")) { try { Scanner scan = new Scanner(new File(root + separator + newSim + separator + ss)); if (scan.hasNextLine()) { sbmlLoadFile = scan.nextLine(); sbmlLoadFile = sbmlLoadFile.split(separator)[sbmlLoadFile .split(separator).length - 1]; gcmFile = sbmlLoadFile; if (sbmlLoadFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + sbmlLoadFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); sbmlLoadFile = root + separator + newSim + separator + sbmlLoadFile.replace(".gcm", ".sbml"); network.mergeSBML(sbmlLoadFile); } else { sbmlLoadFile = root + separator + sbmlLoadFile; } } while (scan.hasNextLine()) { scan.nextLine(); } scan.close(); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load sbml file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } refreshTree(); JTabbedPane simTab = new JTabbedPane(); Reb2Sac reb2sac = new Reb2Sac(sbmlLoadFile, sbmlFile, root, this, newSim, log, simTab, propertiesFile); simTab.addTab("Simulation Options", reb2sac); simTab.getComponentAt(simTab.getComponents().length - 1).setName("Simulate"); simTab.addTab("Abstraction Options", reb2sac.getAdvanced()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); // simTab.addTab("Advanced Options", reb2sac.getProperties()); // simTab.getComponentAt(simTab.getComponents().length - // 1).setName(""); if (gcmFile.contains(".gcm")) { GCM2SBMLEditor gcm = new GCM2SBMLEditor(root + separator, gcmFile, this, log, true, newSim, root + separator + newSim + separator + newSim + ".sim", reb2sac); reb2sac.setGcm(gcm); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", gcm); simTab.getComponentAt(simTab.getComponents().length - 1).setName("GCM Editor"); } else { SBML_Editor sbml = new SBML_Editor(sbmlLoadFile, reb2sac, log, this, root + separator + newSim, root + separator + newSim + separator + newSim + ".sim"); reb2sac.setSbml(sbml); // sbml.addMouseListener(this); simTab.addTab("Parameter Editor", sbml); simTab.getComponentAt(simTab.getComponents().length - 1).setName("SBML Editor"); simTab.addTab("SBML Elements", sbml.getElementsPanel()); simTab.getComponentAt(simTab.getComponents().length - 1).setName(""); } Graph tsdGraph = reb2sac.createGraph(null); // tsdGraph.addMouseListener(this); simTab.addTab("TSD Graph", tsdGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("TSD Graph"); Graph probGraph = reb2sac.createProbGraph(null); // probGraph.addMouseListener(this); simTab.addTab("Probability Graph", probGraph); simTab.getComponentAt(simTab.getComponents().length - 1).setName("ProbGraph"); /* * JLabel noData = new JLabel("No data available"); Font font = * noData.getFont(); font = font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("TSD Graph", noData); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("TSD Graph"); JLabel noData1 = new JLabel("No data * available"); Font font1 = noData1.getFont(); font1 = * font1.deriveFont(Font.BOLD, 42.0f); noData1.setFont(font1); * noData1.setHorizontalAlignment(SwingConstants.CENTER); * simTab.addTab("Probability Graph", noData1); * simTab.getComponentAt(simTab.getComponents().length - * 1).setName("ProbGraph"); */ tab.setComponentAt(tab.getSelectedIndex(), simTab); tab.setTitleAt(tab.getSelectedIndex(), newSim); tab.getComponentAt(tab.getSelectedIndex()).setName(newSim); } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to copy simulation.", "Error", JOptionPane.ERROR_MESSAGE); } } public void refreshLearn(String learnName, boolean data) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(learnName)) { for (int j = 0; j < ((JTabbedPane) tab.getComponentAt(i)).getComponentCount(); j++) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName().equals( "TSD Graph")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Graph) { ((Graph) ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j)) .refresh(); } else { ((JTabbedPane) tab.getComponentAt(i)) .setComponentAt(j, new Graph(null, "amount", learnName + " data", "tsd.printer", root + separator + learnName, "time", this, null, log, null, true, true)); ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).setName( "TSD Graph"); } /* * } else { JLabel noData1 = new JLabel("No data * available"); Font font = noData1.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData1.setFont(font); noData1.setHorizontalAlignment * (SwingConstants.CENTER); ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData1); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("TSD Graph"); } */ } else if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j).getName() .equals("Learn")) { // if (data) { if (((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) instanceof Learn) { } else { if (lema) { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new LearnLHPN(root + separator + learnName, log, this)); } else { ((JTabbedPane) tab.getComponentAt(i)).setComponentAt(j, new Learn( root + separator + learnName, log, this)); } ((JTabbedPane) tab.getComponentAt(i)).getComponentAt(j) .setName("Learn"); } /* * } else { JLabel noData = new JLabel("No data * available"); Font font = noData.getFont(); font = * font.deriveFont(Font.BOLD, 42.0f); * noData.setFont(font); * noData.setHorizontalAlignment(SwingConstants.CENTER); * ((JTabbedPane) * tab.getComponentAt(i)).setComponentAt(j, noData); * ((JTabbedPane) * tab.getComponentAt(i)).getComponentAt(j * ).setName("Learn"); } */ } } } } } private void updateGCM() { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).contains(".gcm")) { ((GCM2SBMLEditor) tab.getComponentAt(i)).reloadFiles(); tab.setTitleAt(i, ((GCM2SBMLEditor) tab.getComponentAt(i)).getFilename()); } } } public void updateViews(String updatedFile) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); String properties = root + separator + tab + separator + tab + ".sim"; String properties2 = root + separator + tab + separator + tab + ".lrn"; if (new File(properties).exists()) { String check = ""; try { Scanner s = new Scanner(new File(properties)); if (s.hasNextLine()) { check = s.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } s.close(); } catch (Exception e) { } if (check.equals(updatedFile)) { JTabbedPane sim = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < sim.getTabCount(); j++) { if (sim.getComponentAt(j).getName().equals("SBML Editor")) { new File(properties).renameTo(new File(properties.replace(".sim", ".temp"))); boolean dirty = ((SBML_Editor) (sim.getComponentAt(j))).isDirty(); ((SBML_Editor) (sim.getComponentAt(j))).save(false, "", true); if (updatedFile.contains(".gcm")) { GCMParser parser = new GCMParser(root + separator + updatedFile); GeneticNetwork network = parser.buildNetwork(); GeneticNetwork.setRoot(root + File.separator); network.mergeSBML(root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + tab + separator + updatedFile.replace(".gcm", ".sbml")); } else { ((SBML_Editor) (sim.getComponentAt(j))).updateSBML(i, j, root + separator + updatedFile); } ((SBML_Editor) (sim.getComponentAt(j))).setDirty(dirty); new File(properties).delete(); new File(properties.replace(".sim", ".temp")).renameTo(new File( properties)); sim.setComponentAt(j + 1, ((SBML_Editor) (sim.getComponentAt(j))) .getElementsPanel()); sim.getComponentAt(j + 1).setName(""); } } } } if (new File(properties2).exists()) { String check = ""; try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(properties2)); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { JOptionPane.showMessageDialog(frame, "Unable to load background file.", "Error", JOptionPane.ERROR_MESSAGE); check = ""; } if (check.equals(updatedFile)) { JTabbedPane learn = ((JTabbedPane) (this.tab.getComponentAt(i))); for (int j = 0; j < learn.getTabCount(); j++) { if (learn.getComponentAt(j).getName().equals("Data Manager")) { ((DataManager) (learn.getComponentAt(j))).updateSpecies(); } else if (learn.getComponentAt(j).getName().equals("Learn")) { ((Learn) (learn.getComponentAt(j))).updateSpecies(root + separator + updatedFile); } else if (learn.getComponentAt(j).getName().contains("Graph")) { ((Graph) (learn.getComponentAt(j))).refresh(); } } } } ArrayList<String> saved = new ArrayList<String>(); if (this.tab.getComponentAt(i) instanceof GCM2SBMLEditor) { saved.add(this.tab.getTitleAt(i)); GCM2SBMLEditor gcm = (GCM2SBMLEditor) this.tab.getComponentAt(i); if (gcm.getSBMLFile().equals(updatedFile)) { gcm.save("save"); } } String[] files = new File(root).list(); for (String s : files) { if (s.contains(".gcm") && !saved.contains(s)) { GCMFile gcm = new GCMFile(); gcm.load(root + separator + s); if (gcm.getSBMLFile().equals(updatedFile)) { updateViews(s); } } } } } private void enableTabMenu(int selectedTab) { treeSelected = false; // log.addText("tab menu"); if (selectedTab != -1) { tab.setSelectedIndex(selectedTab); } Component comp = tab.getSelectedComponent(); // if (comp != null) { // log.addText(comp.toString()); // } viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); if (comp instanceof GCM2SBMLEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof LHPNEditor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(true); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(true); viewLog.setEnabled(false); saveParam.setEnabled(false); } else if (comp instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(true); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(true); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(true); saveTemp.setEnabled(true); } else if (comp instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(true); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) comp).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (comp instanceof JTabbedPane) { Component component = ((JTabbedPane) comp).getSelectedComponent(); Boolean learn = false; for (Component c : ((JTabbedPane) comp).getComponents()) { if (c instanceof Learn) { learn = true; } } // int index = tab.getSelectedIndex(); if (component instanceof Graph) { saveButton.setEnabled(true); saveasButton.setEnabled(true); if (learn) { runButton.setEnabled(false); } else { runButton.setEnabled(true); } refreshButton.setEnabled(true); checkButton.setEnabled(false); exportButton.setEnabled(true); save.setEnabled(true); if (learn) { run.setEnabled(false); } else { run.setEnabled(true); } saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(true); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(true); check.setEnabled(false); export.setEnabled(true); exportMenu.setEnabled(true); if (((Graph) component).isTSDGraph()) { exportCsv.setEnabled(true); exportDat.setEnabled(true); exportTsd.setEnabled(true); } else { exportCsv.setEnabled(false); exportDat.setEnabled(false); exportTsd.setEnabled(false); } exportEps.setEnabled(true); exportJpg.setEnabled(true); exportPdf.setEnabled(true); exportPng.setEnabled(true); exportSvg.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Reb2Sac) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof SBML_Editor) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof Learn) { if (((Learn) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((Learn) component).getSaveGcmEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((Learn) component).getSaveGcmEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((Learn) component).getViewGcmEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((Learn) component).getViewLogEnabled()); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof LearnLHPN) { if (((LearnLHPN) component).isComboSelected()) { frame.getGlassPane().setVisible(false); } saveButton.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(((LearnLHPN) component).getSaveLhpnEnabled()); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewCircuit.setEnabled(((LearnLHPN) component).getViewLhpnEnabled()); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(((LearnLHPN) component).getViewLogEnabled()); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof DataManager) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(true); saveAsGcm.setEnabled(true); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JPanel) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (component instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(false); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else if (comp instanceof JPanel) { if (comp.getName().equals("Verification")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); viewRules.setEnabled(false); // viewTrace.setEnabled(((Verification) // comp).getViewTraceEnabled()); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); // viewLog.setEnabled(((Verification) // comp).getViewLogEnabled()); viewLog.setEnabled(true); saveParam.setEnabled(true); } else if (comp.getName().equals("Synthesis")) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(true); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(true); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewModel.setEnabled(true); // viewRules.setEnabled(((Synthesis) // comp).getViewRulesEnabled()); // viewTrace.setEnabled(((Synthesis) // comp).getViewTraceEnabled()); // viewCircuit.setEnabled(((Synthesis) // comp).getViewCircuitEnabled()); // viewLog.setEnabled(((Synthesis) comp).getViewLogEnabled()); viewRules.setEnabled(true); viewTrace.setEnabled(true); viewCircuit.setEnabled(true); viewLog.setEnabled(true); saveParam.setEnabled(false); } } else if (comp instanceof JScrollPane) { saveButton.setEnabled(true); saveasButton.setEnabled(true); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(true); run.setEnabled(false); saveAs.setEnabled(true); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(true); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else { saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); exportMenu.setEnabled(false); viewCircuit.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); } private void enableTreeMenu() { treeSelected = true; // log.addText(tree.getFile()); saveButton.setEnabled(false); saveasButton.setEnabled(false); runButton.setEnabled(false); refreshButton.setEnabled(false); checkButton.setEnabled(false); exportButton.setEnabled(false); exportMenu.setEnabled(false); save.setEnabled(false); run.setEnabled(false); saveAs.setEnabled(false); saveAsMenu.setEnabled(false); saveAsGcm.setEnabled(false); saveAsLhpn.setEnabled(false); saveAsGraph.setEnabled(false); saveAsSbml.setEnabled(false); saveAsTemplate.setEnabled(false); if (tree.getFile() != null) { if (tree.getFile().length() > 4 && tree.getFile().substring(tree.getFile().length() - 5).equals(".sbml") || tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".xml")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graph"); viewModBrowser.setEnabled(true); createAnal.setEnabled(true); createAnal.setActionCommand("simulate"); createLearn.setEnabled(true); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".gcm")) { viewModGraph.setEnabled(true); viewModGraph.setActionCommand("graphDot"); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSbml.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewModel.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".grf")) { viewModel.setEnabled(false); viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".vhd")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 1 && tree.getFile().substring(tree.getFile().length() - 2).equals(".g")) { viewModel.setEnabled(true); viewModGraph.setEnabled(true); viewModBrowser.setEnabled(false); createAnal.setEnabled(true); createAnal.setActionCommand("createSim"); createLearn.setEnabled(true); createSynth.setEnabled(true); createVer.setEnabled(true); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); if (new File(root + separator + "atacs.log").exists()) { viewLog.setEnabled(true); } else { viewLog.setEnabled(false); } saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".csp")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".hse")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".unc")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (tree.getFile().length() > 3 && tree.getFile().substring(tree.getFile().length() - 4).equals(".rsg")) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSynth.setEnabled(false); createVer.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } else if (new File(tree.getFile()).isDirectory() && !tree.getFile().equals(root)) { boolean sim = false; boolean synth = false; boolean ver = false; boolean learn = false; for (String s : new File(tree.getFile()).list()) { if (s.length() > 3 && s.substring(s.length() - 4).equals(".sim")) { sim = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".syn")) { synth = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".ver")) { ver = true; } else if (s.length() > 4 && s.substring(s.length() - 4).equals(".lrn")) { learn = true; } } if (sim || synth || ver || learn) { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(true); rename.setEnabled(true); delete.setEnabled(true); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } else { viewModGraph.setEnabled(false); viewModBrowser.setEnabled(false); createAnal.setEnabled(false); createLearn.setEnabled(false); createSbml.setEnabled(false); refresh.setEnabled(false); check.setEnabled(false); export.setEnabled(false); copy.setEnabled(false); rename.setEnabled(false); delete.setEnabled(false); viewRules.setEnabled(false); viewTrace.setEnabled(false); viewCircuit.setEnabled(false); viewLog.setEnabled(false); saveParam.setEnabled(false); saveSbml.setEnabled(false); saveTemp.setEnabled(false); } } } public String getRoot() { return root; } public void setGlassPane(boolean visible) { frame.getGlassPane().setVisible(visible); } public boolean overwrite(String fullPath, String name) { if (new File(fullPath).exists()) { Object[] options = { "Overwrite", "Cancel" }; // int value = JOptionPane.showOptionDialog(frame, name + " already // exists." // + "\nDo you want to overwrite?", "Overwrite", // JOptionPane.YES_NO_OPTION, // JOptionPane.PLAIN_MESSAGE, null, options, options[0]); // if (value == JOptionPane.YES_OPTION) { String[] views = canDelete(name); if (views.length == 0) { for (int i = 0; i < tab.getTabCount(); i++) { if (tab.getTitleAt(i).equals(name)) { tab.remove(i); } } File dir = new File(fullPath); if (dir.isDirectory()) { deleteDir(dir); } else { System.gc(); dir.delete(); } return true; } else { String view = ""; for (int i = 0; i < views.length; i++) { if (i == views.length - 1) { view += views[i]; } else { view += views[i] + "\n"; } } String message = "Unable to overwrite file." + "\nIt is linked to the following views:\n" + view + "\nDelete these views first."; JTextArea messageArea = new JTextArea(message); messageArea.setEditable(false); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(300, 300)); scroll.setPreferredSize(new Dimension(300, 300)); scroll.setViewportView(messageArea); JOptionPane.showMessageDialog(frame, scroll, "Unable To Overwrite File", JOptionPane.ERROR_MESSAGE); return false; } // } // else { // return false; // } } else { return true; } } public void updateOpenSBML(String sbmlName) { for (int i = 0; i < tab.getTabCount(); i++) { String tab = this.tab.getTitleAt(i); if (sbmlName.equals(tab)) { if (this.tab.getComponentAt(i) instanceof SBML_Editor) { SBML_Editor newSBML = new SBML_Editor(root + separator + sbmlName, null, log, this, null, null); this.tab.setComponentAt(i, newSBML); this.tab.getComponentAt(i).setName("SBML Editor"); newSBML.save(false, "", false); } } } } private String[] canDelete(String filename) { ArrayList<String> views = new ArrayList<String>(); String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; } scan.close(); } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; } else { check = ""; } } catch (Exception e) { check = ""; } } if (check.equals(filename)) { views.add(s); } } } String[] usingViews = views.toArray(new String[0]); sort(usingViews); return usingViews; } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } private void reassignViews(String oldName, String newName) { String[] files = new File(root).list(); for (String s : files) { if (new File(root + separator + s).isDirectory()) { String check = ""; if (new File(root + separator + s + separator + s + ".sim").exists()) { try { ArrayList<String> copy = new ArrayList<String>(); Scanner scan = new Scanner(new File(root + separator + s + separator + s + ".sim")); if (scan.hasNextLine()) { check = scan.nextLine(); check = check.split(separator)[check.split(separator).length - 1]; if (check.equals(oldName)) { while (scan.hasNextLine()) { copy.add(scan.nextLine()); } scan.close(); FileOutputStream out = new FileOutputStream(new File(root + separator + s + separator + s + ".sim")); out.write((newName + "\n").getBytes()); for (String cop : copy) { out.write((cop + "\n").getBytes()); } out.close(); } else { scan.close(); } } } catch (Exception e) { } } else if (new File(root + separator + s + separator + s + ".lrn").exists()) { try { Properties p = new Properties(); FileInputStream load = new FileInputStream(new File(root + separator + s + separator + s + ".lrn")); p.load(load); load.close(); if (p.containsKey("genenet.file")) { String[] getProp = p.getProperty("genenet.file").split(separator); check = getProp[getProp.length - 1]; if (check.equals(oldName)) { p.setProperty("genenet.file", newName); FileOutputStream store = new FileOutputStream(new File(root + separator + s + separator + s + ".lrn")); p.store(store, "Learn File Data"); store.close(); } } } catch (Exception e) { } } } } } protected JButton makeToolButton(String imageName, String actionCommand, String toolTipText, String altText) { // URL imageURL = BioSim.class.getResource(imageName); // Create and initialize the button. JButton button = new JButton(); button.setActionCommand(actionCommand); button.setToolTipText(toolTipText); button.addActionListener(this); button.setIcon(new ImageIcon(imageName)); // if (imageURL != null) { //image found // button.setIcon(new ImageIcon(imageURL, altText)); // } else { //no image found // button.setText(altText); // System.err.println("Resource not found: " // + imageName); // } return button; } }
Imports LHPNs correctly (runs ATACS to get rid of implicit places, etc.)
gui/src/biomodelsim/BioSim.java
Imports LHPNs correctly (runs ATACS to get rid of implicit places, etc.)
<ide><path>ui/src/biomodelsim/BioSim.java <ide> } <ide> in.close(); <ide> out.close(); <add> File work = new File(root); <add> String oldName = root + separator + file[file.length - 1]; <add> String newName = oldName.replace(".g", "_NEW.g"); <add> Process atacs = Runtime.getRuntime().exec("atacs -llsl " + oldName, null, work); <add> atacs.waitFor(); <add> FileOutputStream old = new FileOutputStream(new File(oldName)); <add> FileInputStream newFile = new FileInputStream(new File(newName)); <add> int readNew = newFile.read(); <add> while (readNew != -1) { <add> old.write(readNew); <add> readNew = newFile.read(); <add> } <add> old.close(); <add> newFile.close(); <add> new File(newName).delete(); <ide> refreshTree(); <ide> } <ide> catch (Exception e1) { <add> e1.printStackTrace(); <ide> JOptionPane.showMessageDialog(frame, "Unable to import file.", "Error", <ide> JOptionPane.ERROR_MESSAGE); <ide> }
JavaScript
mit
94cfae717829859a26e59f45fee3cd3d732c145b
0
ftlabs/fruitmachine-media
/* jshint node: true, browser: true */ /** * Media Helper. * * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All rights reserved] */ 'use strict'; /** * Locals */ var mm = window.matchMedia; require('setimmediate'); var Promise = require('es6-promise').Promise; /** * Exports */ module.exports = function(module) { var setImmediateId = 0; var callbacks = []; var callbackProcessList = []; var processing = 0; module.on('initialize', function(options) { this._media = {}; var media = this.media; var states = expandStates(this.states || {}); var state; var name; for (var query in media) { if (media.hasOwnProperty(query)) { name = media[query]; state = states[name] || {}; this._media[name] = { query: query, setup: state.setup, teardown: state.teardown }; } } }); module.on('setup', function() { var state; var matcher; for (var name in this._media) { if (this._media.hasOwnProperty(name)) { state = this._media[name]; matcher = state.matcher = mm(state.query); matcher.addListener(state.cb = callback(name)); // Call setup on the current media state. if (matcher.matches) setup(name); } } }); module.on('before teardown', function() { var state; var matcher; for (var name in this._media) { if (this._media.hasOwnProperty(name)) { state = this._media[name]; matcher = state.matcher; matcher.removeListener(state.cb); if (matcher.matches) teardown(name, { fromDOM: false }); } } }); function processStateChanges(callback) { processing = true; if(callbackProcessList.length) { // Pull oldest state change var item = callbackProcessList.shift(); Promise.all([item.action(item.name)]).then(function () { module.fireStatic('statechange'); processStateChanges(callback); }); } else { processing = false; if (callback) callback(); } } function callback(name) { return function(data) { var state = module._media[name]; // NOTE:WP:Don't do anything if the // matches state has not changed. // This is to work around a strange bug, // whereby sometimes the callback fires // twice. // // I'm not sure if this a browser // bug, or a bug we have caused. if (state.matches === data.matches) return; // Either setup or teardown if (data.matches) { // Add setups to the beginning callbacks.push({ name: name, action: setup }); } else { // Add teardowns to the end callbacks.unshift({ name: name, action: teardown }); } if (!setImmediateId) { // Allow for all state changes to be registered. (In order of teardown -> setup) // Concatenate this to the list of pending state changes. // Trigger processStateChanges if it is not already running. setImmediateId = setImmediate(function() { setImmediateId = 0; callbackProcessList = callbackProcessList.concat(callbacks); callbacks = []; if (!processing) processStateChanges(); }); } // Update the matches state state.matches = data.matches; }; } function setup(name) { if (typeof name !== "string") return; module.el.classList.add(name); return run('setup', { on: name }); } function teardown(name, options) { if (typeof name !== "string") return; var fromDOM = (!options || options.fromDOM !== false); if (fromDOM) { module.el.classList.remove(name); } return run('teardown', { on: name, fromDOM: fromDOM }); } function run(method, options) { var fn = module._media[options.on][method]; var result = fn && fn.call(module, options); // Filter out any non promise results. return result === undefined || !!result.then ? result : undefined; } }; // This allows multiple breakpoints to trigger one function. function expandStates(states) { var expanded = {}; var contents; for (var names in states) { if (states.hasOwnProperty(names)) { contents = states[names]; if (~names.indexOf(' ')) { names.split(' ').forEach(copy); } else { expanded[names] = contents; } } } function copy(name) { expanded[name] = contents; } return expanded; }
media.js
/* jshint node: true, browser: true */ /** * Media Helper. * * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All rights reserved] */ 'use strict'; /** * Locals */ var mm = window.matchMedia; require('setimmediate'); var Promise = require('es6-promise').Promise; /** * Exports */ module.exports = function(module) { var setImmediateId = 0; var callbacks = []; var callbackProcessList = []; var processing = 0; module.on('initialize', function(options) { this._media = {}; var media = this.media; var states = expandStates(this.states || {}); var state; var name; for (var query in media) { if (media.hasOwnProperty(query)) { name = media[query]; state = states[name] || {}; this._media[name] = { query: query, setup: state.setup, teardown: state.teardown }; } } }); module.on('setup', function() { var state; var matcher; for (var name in this._media) { if (this._media.hasOwnProperty(name)) { state = this._media[name]; matcher = state.matcher = mm(state.query); matcher.addListener(state.cb = callback(name)); // Call setup on the current media state. if (matcher.matches) setup(name); } } }); module.on('before teardown', function() { var state; var matcher; for (var name in this._media) { if (this._media.hasOwnProperty(name)) { state = this._media[name]; matcher = state.matcher; matcher.removeListener(state.cb); if (matcher.matches) teardown(name, { fromDOM: false }); } } }); function processStateChanges(callback) { processing = true; if(callbackProcessList.length) { // Pull oldest state change var item = callbackProcessList.shift(); Promise.all([item.action(item.name)]).then(function () { module.fireStatic('statechange'); processStateChanges(callback); }); } else { processing = false; callback(); } } function callback(name) { return function(data) { var state = module._media[name]; // NOTE:WP:Don't do anything if the // matches state has not changed. // This is to work around a strange bug, // whereby sometimes the callback fires // twice. // // I'm not sure if this a browser // bug, or a bug we have caused. if (state.matches === data.matches) return; // Either setup or teardown if (data.matches) { // Add setups to the beginning callbacks.push({ name: name, action: setup }); } else { // Add teardowns to the end callbacks.unshift({ name: name, action: teardown }); } if (!setImmediateId) { // Allow for all state changes to be registered. (In order of teardown -> setup) // Concatenate this to the list of pending state changes. // Trigger processStateChanges if it is not already running. setImmediateId = setImmediate(function() { setImmediateId = 0; callbackProcessList = callbackProcessList.concat(callbacks); callbacks = []; if (!processing) processStateChanges(); }); } // Update the matches state state.matches = data.matches; }; } function setup(name) { if (typeof name !== "string") return; module.el.classList.add(name); return run('setup', { on: name }); } function teardown(name, options) { if (typeof name !== "string") return; var fromDOM = (!options || options.fromDOM !== false); if (fromDOM) { module.el.classList.remove(name); } return run('teardown', { on: name, fromDOM: fromDOM }); } function run(method, options) { var fn = module._media[options.on][method]; var result = fn && fn.call(module, options); // Filter out any non promise results. return result === undefined || !!result.then ? result : undefined; } }; // This allows multiple breakpoints to trigger one function. function expandStates(states) { var expanded = {}; var contents; for (var names in states) { if (states.hasOwnProperty(names)) { contents = states[names]; if (~names.indexOf(' ')) { names.split(' ').forEach(copy); } else { expanded[names] = contents; } } } function copy(name) { expanded[name] = contents; } return expanded; }
Added callback check)
media.js
Added callback check)
<ide><path>edia.js <ide> }); <ide> } else { <ide> processing = false; <del> callback(); <add> if (callback) callback(); <ide> } <ide> } <ide>
Java
apache-2.0
b31fa744ffb9e70b682b2a9a1bffc22363c1beb5
0
coinspark/sparkbit-bitcoinj
/* * SparkBit's Bitcoinj * * Copyright 2014 Coin Sciences Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.coinspark.core; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Sha256Hash; import com.google.bitcoin.core.StoredBlock; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Block store extension. * Stores hashes of all blocks in the blockchain. * This class should be used only in bitcoinj. */ public class CSBlockHeaderStore { private static final Logger log = LoggerFactory.getLogger(CSBlockHeaderStore.class); private static final String FULL_BLOCK_HASHES_SUFFIX = ".fbhchain"; private static final int FULL_BLOCK_HASHES_SIZE = 32; private String fileName; private boolean isCorrupted; private NetworkParameters networkParameters; /** * Initializes block store. Create new if needed. * @param NetworkParameters * @param FilePrefix .fbchain file prefix */ public CSBlockHeaderStore(NetworkParameters NetworkParameters,String FilePrefix) { fileName = FilePrefix + FULL_BLOCK_HASHES_SUFFIX; networkParameters = NetworkParameters; isCorrupted=false; File fbhStoreFile = new File(fileName); boolean bfbhStoreCreatedNew = !fbhStoreFile.exists(); if(bfbhStoreCreatedNew) { Path path = Paths.get(fileName); try { Files.write(path, networkParameters.getGenesisBlock().getHash().getBytes()); } catch (IOException ex) { isCorrupted=true; log.error("Cannot create headers file " + ex.getClass().getName() + " " + ex.getMessage()); } } } /** * * @return File name of extended block store */ public String getFileName() { return fileName; } /** * Puts new block hash in the file. * @param block * @return */ public boolean put(StoredBlock block) { if(isCorrupted) { log.error("Header file corrupted"); return false; } RandomAccessFile aFile; try { aFile = new RandomAccessFile(fileName, "rw"); } catch (FileNotFoundException ex) { log.error("Cannot open header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } long fileSize; try { fileSize = aFile.length(); } catch (IOException ex) { log.error("Cannot get header file size " + ex.getClass().getName() + " " + ex.getMessage()); return false; } if(fileSize < block.getHeight()*FULL_BLOCK_HASHES_SIZE) { log.error("Header file too small: block " + block.getHeight() + ", file size " + fileSize); byte [] nullhash=new byte [32]; for(int i=0;i<32;i++) { nullhash[i]=0; } try { aFile.seek(fileSize); } catch (IOException ex) { log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); return false; } while(fileSize < block.getHeight()*FULL_BLOCK_HASHES_SIZE) { try { aFile.write(nullhash); } catch (IOException ex) { log.error("Cannot add empty block to header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } fileSize+=32; } // return false; } else { try { aFile.seek(block.getHeight()*FULL_BLOCK_HASHES_SIZE); } catch (IOException ex) { log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); return false; } } try { aFile.write(block.getHeader().getHash().getBytes()); } catch (IOException ex) { log.error("Cannot add block to header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } try { aFile.close(); } catch (IOException ex) { log.error("Cannot close header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } return true; } /** * * @param height * @return hash of the block with specified height */ public Sha256Hash getHash(int height) { Sha256Hash hash=Sha256Hash.ZERO_HASH; if(isCorrupted) { log.error("Header file corrupted"); return hash; } RandomAccessFile aFile; try { aFile = new RandomAccessFile(fileName, "r"); } catch (FileNotFoundException ex) { log.error("Cannot open header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } long fileSize; try { fileSize = aFile.length(); } catch (IOException ex) { log.error("Cannot get header file size " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } if(fileSize<(height+1)*FULL_BLOCK_HASHES_SIZE) { log.error("Cannot read block hash, header file too small: block " + height + ", file size " + fileSize); return hash; } try { aFile.seek(height*FULL_BLOCK_HASHES_SIZE); } catch (IOException ex) { log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); } byte[] bytes=new byte[FULL_BLOCK_HASHES_SIZE]; try { aFile.read(bytes); } catch (IOException ex) { log.error("Cannot read block hash from header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } try { aFile.close(); } catch (IOException ex) { log.error("Cannot close header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } hash=new Sha256Hash(bytes); return hash; } }
core/src/main/java/org/coinspark/core/CSBlockHeaderStore.java
/* * SparkBit's Bitcoinj * * Copyright 2014 Coin Sciences Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.coinspark.core; import com.google.bitcoin.core.NetworkParameters; import com.google.bitcoin.core.Sha256Hash; import com.google.bitcoin.core.StoredBlock; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Block store extension. * Stores hashes of all blocks in the blockchain. * This class should be used only in bitcoinj. */ public class CSBlockHeaderStore { private static final Logger log = LoggerFactory.getLogger(CSBlockHeaderStore.class); private static final String FULL_BLOCK_HASHES_SUFFIX = ".fbhchain"; private static final int FULL_BLOCK_HASHES_SIZE = 32; private String fileName; private boolean isCorrupted; private NetworkParameters networkParameters; /** * Initializes block store. Create new if needed. * @param NetworkParameters * @param FilePrefix .fbchain file prefix */ public CSBlockHeaderStore(NetworkParameters NetworkParameters,String FilePrefix) { fileName = FilePrefix + FULL_BLOCK_HASHES_SUFFIX; networkParameters = NetworkParameters; isCorrupted=false; File fbhStoreFile = new File(fileName); boolean bfbhStoreCreatedNew = !fbhStoreFile.exists(); if(bfbhStoreCreatedNew) { Path path = Paths.get(fileName); try { Files.write(path, networkParameters.getGenesisBlock().getHash().getBytes()); } catch (IOException ex) { isCorrupted=true; log.error("Cannot create headers file " + ex.getClass().getName() + " " + ex.getMessage()); } } } /** * * @return File name of extended block store */ public String getFileName() { return fileName; } /** * Puts new block hash in the file. * @param block * @return */ public boolean put(StoredBlock block) { if(isCorrupted) { log.error("Header file corrupted"); return false; } RandomAccessFile aFile; try { aFile = new RandomAccessFile(fileName, "rw"); } catch (FileNotFoundException ex) { log.error("Cannot open header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } long fileSize; try { fileSize = aFile.length(); } catch (IOException ex) { log.error("Cannot get header file size " + ex.getClass().getName() + " " + ex.getMessage()); return false; } if(fileSize < block.getHeight()*FULL_BLOCK_HASHES_SIZE) { log.error("Cannot store block, header file too small: block " + block.getHeight() + ", file size " + fileSize); return false; } try { aFile.seek(block.getHeight()*FULL_BLOCK_HASHES_SIZE); } catch (IOException ex) { log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); return false; } try { aFile.write(block.getHeader().getHash().getBytes()); } catch (IOException ex) { log.error("Cannot add block to header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } try { aFile.close(); } catch (IOException ex) { log.error("Cannot close header file " + ex.getClass().getName() + " " + ex.getMessage()); return false; } return true; } /** * * @param height * @return hash of the block with specified height */ public Sha256Hash getHash(int height) { Sha256Hash hash=Sha256Hash.ZERO_HASH; if(isCorrupted) { log.error("Header file corrupted"); return hash; } RandomAccessFile aFile; try { aFile = new RandomAccessFile(fileName, "r"); } catch (FileNotFoundException ex) { log.error("Cannot open header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } long fileSize; try { fileSize = aFile.length(); } catch (IOException ex) { log.error("Cannot get header file size " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } if(fileSize<(height+1)*FULL_BLOCK_HASHES_SIZE) { log.error("Cannot read block hash, header file too small: block " + height + ", file size " + fileSize); return hash; } try { aFile.seek(height*FULL_BLOCK_HASHES_SIZE); } catch (IOException ex) { log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); } byte[] bytes=new byte[FULL_BLOCK_HASHES_SIZE]; try { aFile.read(bytes); } catch (IOException ex) { log.error("Cannot read block hash from header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } try { aFile.close(); } catch (IOException ex) { log.error("Cannot close header file " + ex.getClass().getName() + " " + ex.getMessage()); return hash; } hash=new Sha256Hash(bytes); return hash; } }
Null hash in fbchain file for missing block
core/src/main/java/org/coinspark/core/CSBlockHeaderStore.java
Null hash in fbchain file for missing block
<ide><path>ore/src/main/java/org/coinspark/core/CSBlockHeaderStore.java <ide> <ide> if(fileSize < block.getHeight()*FULL_BLOCK_HASHES_SIZE) <ide> { <del> log.error("Cannot store block, header file too small: block " + block.getHeight() + ", file size " + fileSize); <del> return false; <del> } <del> <del> try { <del> aFile.seek(block.getHeight()*FULL_BLOCK_HASHES_SIZE); <del> } catch (IOException ex) { <del> log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); <del> return false; <add> log.error("Header file too small: block " + block.getHeight() + ", file size " + fileSize); <add> byte [] nullhash=new byte [32]; <add> for(int i=0;i<32;i++) <add> { <add> nullhash[i]=0; <add> } <add> try { <add> aFile.seek(fileSize); <add> } catch (IOException ex) { <add> log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); <add> return false; <add> } <add> while(fileSize < block.getHeight()*FULL_BLOCK_HASHES_SIZE) <add> { <add> try { <add> aFile.write(nullhash); <add> } catch (IOException ex) { <add> log.error("Cannot add empty block to header file " + ex.getClass().getName() + " " + ex.getMessage()); <add> return false; <add> } <add> fileSize+=32; <add> } <add>// return false; <add> } <add> else <add> { <add> try { <add> aFile.seek(block.getHeight()*FULL_BLOCK_HASHES_SIZE); <add> } catch (IOException ex) { <add> log.error("Cannot set headers file position " + ex.getClass().getName() + " " + ex.getMessage()); <add> return false; <add> } <ide> } <ide> <ide> try {
Java
bsd-3-clause
232c7ccdc09be5ac30d6455a9e4feb3a2659415d
0
sfhsfembot/offseason2014
// RobotBuilder Version: 1.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc692.OffSeason2014.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * */ public class gathererDownAndGather extends CommandGroup { public gathererDownAndGather() { // Add Commands here: // e.g. addSequential(new Command1()); // addSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use addParallel() // e.g. addParallel(new Command1()); // addSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. addParallel(new gathererDown()); addParallel(new gathererRollerControl()); //gatherer goes down and gatherer roller is controlled //ND 11/20/14 } }
src/org/usfirst/frc692/OffSeason2014/commands/gathererDownAndGather.java
// RobotBuilder Version: 1.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc692.OffSeason2014.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * */ public class gathererDownAndGather extends CommandGroup { public gathererDownAndGather() { // Add Commands here: // e.g. addSequential(new Command1()); // addSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use addParallel() // e.g. addParallel(new Command1()); // addSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. } }
copy and pasted code
src/org/usfirst/frc692/OffSeason2014/commands/gathererDownAndGather.java
copy and pasted code
<ide><path>rc/org/usfirst/frc692/OffSeason2014/commands/gathererDownAndGather.java <ide> // e.g. if Command1 requires chassis, and Command2 requires arm, <ide> // a CommandGroup containing them would require both the chassis and the <ide> // arm. <add> <add> addParallel(new gathererDown()); <add> addParallel(new gathererRollerControl()); <add> //gatherer goes down and gatherer roller is controlled <add> //ND 11/20/14 <ide> } <ide> }
Java
mit
604b12e7523bec9650b16c0b9db4fa336becb2cb
0
Innovimax-SARL/mix-them
package innovimax.mixthem.operation; import static innovimax.mixthem.MixConstants.*; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Map; import java.util.stream.Stream; /** * <p>Zips two characters.</p> * @see CharOperation * @author Innovimax * @version 1.0 */ public class DefaultCharZipping extends AbstractCharOperation { private final String sep; /** * Constructor * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public DefaultCharZipping(Map<RuleParam, ParamValue> params) { super(params); this.sep = params.containsKey(RuleParam._ZIP_SEP) ? params.get(RuleParam._ZIP_SEP).asString() : DEFAULT_ZIP_SEPARATOR; } @Override public Stream process(int c1, int c2) throws MixException { int len = (c1 != -1 ? 1 : 0) + sep.length() + (c2 != -1 ? 1 : 0); int[] zip = new int[len]; if (c1 != -1) { zip[0] = c1; } for (int i = 0; i < sep.length(); i++) { zip[i + 1] = (int) sep.charAt(i); } if (c2 != -1) { zip[zip.length - 1] = c2; } return Arrays.stream(zip); } }
src/main/java/innovimax/mixthem/operation/DefaultCharZipping.java
package innovimax.mixthem.operation; import static innovimax.mixthem.MixConstants.*; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.arguments.ParamValue; import java.util.Map; /** * <p>Zips two characters.</p> * @see CharOperation * @author Innovimax * @version 1.0 */ public class DefaultCharZipping extends AbstractCharOperation { private final String sep; /** * Constructor * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.arguments.RuleParam * @see innovimax.mixthem.arguments.ParamValue */ public DefaultCharZipping(Map<RuleParam, ParamValue> params) { super(params); this.sep = params.containsKey(RuleParam._ZIP_SEP) ? params.get(RuleParam._ZIP_SEP).asString() : DEFAULT_ZIP_SEPARATOR; } @Override public int[] process(int c1, int c2) throws MixException { int len = (c1 != -1 ? 1 : 0) + sep.length() + (c2 != -1 ? 1 : 0); int[] zip = new int[len]; if (c1 != -1) { zip[0] = c1; } for (int i = 0; i < sep.length(); i++) { zip[i + 1] = (int) sep.charAt(i); } if (c2 != -1) { zip[zip.length - 1] = c2; } return zip; } }
returns array as stream
src/main/java/innovimax/mixthem/operation/DefaultCharZipping.java
returns array as stream
<ide><path>rc/main/java/innovimax/mixthem/operation/DefaultCharZipping.java <ide> import innovimax.mixthem.arguments.ParamValue; <ide> <ide> import java.util.Map; <add>import java.util.stream.Stream; <ide> <ide> /** <ide> * <p>Zips two characters.</p> <ide> } <ide> <ide> @Override <del> public int[] process(int c1, int c2) throws MixException { <add> public Stream process(int c1, int c2) throws MixException { <ide> int len = (c1 != -1 ? 1 : 0) + sep.length() + (c2 != -1 ? 1 : 0); <ide> int[] zip = new int[len]; <ide> if (c1 != -1) { <ide> zip[0] = c1; <del> } <add> } <ide> for (int i = 0; i < sep.length(); i++) { <ide> zip[i + 1] = (int) sep.charAt(i); <ide> } <ide> if (c2 != -1) { <ide> zip[zip.length - 1] = c2; <ide> } <del> return zip; <add> return Arrays.stream(zip); <ide> } <ide> <ide> }
Java
lgpl-2.1
e768b2a838bf6fa105e6a25faae63a51d8ebe609
0
stokito/libjnvpx,bgrozev/libjitsi,innerverse/libjitsi,HappyYang/libjitsi,bgrozev/libjitsi,jamesbond12/libjitsi,agh1467/libjitsi,agh1467/libjitsi,draekko/libjitsi,jamesbond12/libjitsi,jitsi/libjitsi,stokito/libjnvpx,bebo/libjitsi,gpolitis/libjitsi,ITNano/libjitsi,innerverse/libjitsi,innerverse/libjitsi,bebo/libjitsi,gpolitis/libjitsi,HappyYang/libjitsi,HappyYang/libjitsi,draekko/libjitsi,jamesbond12/libjitsi,jitsi/libjitsi,draekko/libjitsi,jitsi/libjitsi,jitsi/libjitsi,bgrozev/libjitsi,bebo/libjitsi,agh1467/libjitsi,gpolitis/libjitsi,ITNano/libjitsi,ITNano/libjitsi
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.impl.neomedia.rtcp.termination.strategies; import net.sf.fmj.media.rtp.*; import org.jitsi.impl.neomedia.rtcp.*; import org.jitsi.impl.neomedia.rtp.translator.*; import org.jitsi.service.neomedia.*; import java.util.*; import java.util.concurrent.*; /** * Created by gp on 16/07/14. */ public class BasicRTCPTerminationStrategy implements RTCPTerminationStrategy, RTCPPacketTransformer, RTCPReportBuilder { private RTCPTransmitter rtcpTransmitter; /** * A cache of media receiver feedback. It contains both receiver report * blocks and REMB packets. */ protected final FeedbackCache feedbackCache; /** * The cache processor that will be making the RTCP reports coming from * the bridge. */ private FeedbackCacheProcessor feedbackCacheProcessor; public BasicRTCPTerminationStrategy() { this.feedbackCache = new FeedbackCache(); reset(); } /** * The <tt>RTPTranslator</tt> associated with this strategy. */ protected RTPTranslator translator; @Override public RTCPPacket[] makeReports() { if (rtcpTransmitter == null) throw new IllegalStateException("rtcpTransmitter is not set"); RTPTranslator t = this.translator; if (t == null || !(t instanceof RTPTranslatorImpl)) return new RTCPPacket[0]; // Use the SSRC of the bridge that is announced and the endpoints won't // drop the packet. int localSSRC = (int) ((RTPTranslatorImpl)t).getLocalSSRC(null); Vector<RTCPPacket> packets = new Vector<RTCPPacket>(); long time = System.currentTimeMillis(); RTCPReportBlock reports[] = makeReceiverReports(time); RTCPReportBlock firstrep[] = reports; // If the number of sources for which reception statistics are being // reported exceeds 31, the number that will fit into one SR or RR // packet, then additional RR packets SHOULD follow the initial report // packet. if (reports.length > 31) { firstrep = new RTCPReportBlock[31]; System.arraycopy(reports, 0, firstrep, 0, 31); } packets.addElement(new RTCPRRPacket(localSSRC, firstrep)); if (firstrep != reports) { for (int offset = 31; offset < reports.length; offset += 31) { if (reports.length - offset < 31) firstrep = new RTCPReportBlock[reports.length - offset]; System.arraycopy(reports, offset, firstrep, 0, firstrep.length); RTCPRRPacket rrp = new RTCPRRPacket(localSSRC, firstrep); packets.addElement(rrp); } } // Include REMB. // TODO(gp) build REMB packets from scratch. if (this.feedbackCacheProcessor == null) { this.feedbackCacheProcessor = new FeedbackCacheProcessor(feedbackCache); // TODO(gp) make percentile configurable. this.feedbackCacheProcessor.setPercentile(70); } RTCPPacket[] bestReceiverFeedback = feedbackCacheProcessor.makeReports( localSSRC); if (bestReceiverFeedback != null && bestReceiverFeedback.length != 0) { for (RTCPPacket packet : bestReceiverFeedback) { if (packet.type == RTCPPacketType.PSFB && packet instanceof RTCPFBPacket && ((RTCPFBPacket)packet).fmt == RTCPPSFBFormat.REMB) { packets.add(packet); } } } // TODO(gp) for RTCP compound packets MUST contain an SDES packet. // Copy into an array and return. RTCPPacket[] res = new RTCPPacket[packets.size()]; packets.copyInto(res); return res; } private RTCPReportBlock[] makeReceiverReports(long time) { Vector<RTCPReportBlock> reports = new Vector<RTCPReportBlock>(); // Make receiver reports for all known SSRCs. for (Enumeration<SSRCInfo> elements = rtcpTransmitter.cache.cache.elements(); elements.hasMoreElements();) { SSRCInfo info = elements.nextElement(); if (!info.ours && info.sender) { int ssrc = info.ssrc; long lastseq = info.maxseq + info.cycles; int jitter = (int) info.jitter; long lsr = (int) ((info.lastSRntptimestamp & 0x0000ffffffff0000L) >> 16); long dlsr = (int) ((time - info.lastSRreceiptTime) * 65.536000000000001D); int packetslost = (int) (((lastseq - info.baseseq) + 1L) - info.received); if (packetslost < 0) packetslost = 0; double frac = (double) (packetslost - info.prevlost) / (double) (lastseq - info.prevmaxseq); if (frac < 0.0D) frac = 0.0D; int fractionlost =(int) (frac * 256D); RTCPReportBlock receiverReport = new RTCPReportBlock( ssrc, fractionlost, packetslost, lastseq, jitter, lsr, dlsr ); info.prevmaxseq = (int) lastseq; info.prevlost = packetslost; reports.addElement(receiverReport); } } // Copy into an array and return. RTCPReportBlock res[] = new RTCPReportBlock[reports.size()]; reports.copyInto(res); return res; } @Override public void reset() { /* Nothing to do here */ } @Override public void setRTCPTransmitter(RTCPTransmitter rtcpTransmitter) { this.rtcpTransmitter = rtcpTransmitter; } @Override public RTCPPacketTransformer getRTCPPacketTransformer() { return this; } @Override public RTCPReportBuilder getRTCPReportBuilder() { return this; } @Override public void setRTPTranslator(RTPTranslator translator) { this.translator = translator; } /** * 1. Removes receiver report blocks from RRs and SRs and kills REMBs. * 2. Updates the receiver feedback cache. * * @param inPacket * @return */ @Override public RTCPCompoundPacket transformRTCPPacket( RTCPCompoundPacket inPacket) { if (inPacket == null || inPacket.packets == null || inPacket.packets.length == 0) { return inPacket; } Vector<RTCPPacket> outPackets = new Vector<RTCPPacket>( inPacket.packets.length); // These are the data that are of interest to us : RR report blocks and // REMBs. We'll also need the SSRC of the RTCP report sender. RTCPReportBlock[] reports = null; RTCPREMBPacket remb = null; Integer ssrc = 0; // Modify the incoming RTCP packet and/or update the // <tt>feedbackCache</tt>. for (RTCPPacket p : inPacket.packets) { switch (p.type) { case RTCPPacketType.RR: // Grab the receiver report blocks to put them into the // cache after the loop is done and mute the RR. RTCPRRPacket rr = (RTCPRRPacket) p; reports = rr.reports; ssrc = Integer.valueOf(rr.ssrc); break; case RTCPPacketType.SR: // Grab the receiver report blocks to put them into the // cache after the loop is done; mute the receiver report // blocks. RTCPSRPacket sr = (RTCPSRPacket) p; outPackets.add(sr); reports = sr.reports; ssrc = Integer.valueOf(sr.ssrc); sr.reports = new RTCPReportBlock[0]; break; case RTCPPacketType.PSFB: RTCPFBPacket psfb = (RTCPFBPacket) p; switch (psfb.fmt) { case RTCPPSFBFormat.REMB: // NOT adding the REMB in the outPacket as we mute // REMBs from the peers. // // We put it into the feedback cache instead. remb = (RTCPREMBPacket) p; ssrc = Integer.valueOf((int) remb.senderSSRC); break; default: // Pass through everything else, like PLIs and NACKs outPackets.add(psfb); break; } break; default: // Pass through everything else, like PLIs and NACKs outPackets.add(p); break; } } feedbackCache.update(ssrc, reports, remb); RTCPPacket[] outarr = new RTCPPacket[outPackets.size()]; outPackets.copyInto(outarr); RTCPCompoundPacket outPacket = new RTCPCompoundPacket(outarr); return outPacket; } }
src/org/jitsi/impl/neomedia/rtcp/termination/strategies/BasicRTCPTerminationStrategy.java
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jitsi.impl.neomedia.rtcp.termination.strategies; import net.sf.fmj.media.rtp.*; import org.jitsi.impl.neomedia.rtcp.*; import org.jitsi.impl.neomedia.rtp.translator.*; import org.jitsi.service.neomedia.*; import java.util.*; import java.util.concurrent.*; /** * Created by gp on 16/07/14. */ public class BasicRTCPTerminationStrategy implements RTCPTerminationStrategy, RTCPPacketTransformer, RTCPReportBuilder { private RTCPTransmitter rtcpTransmitter; /** * A cache of media receiver feedback. It contains both receiver report * blocks and REMB packets. */ private final FeedbackCache feedbackCache; /** * The cache processor that will be making the RTCP reports coming from * the bridge. */ private FeedbackCacheProcessor feedbackCacheProcessor; public BasicRTCPTerminationStrategy() { this.feedbackCache = new FeedbackCache(); reset(); } /** * The <tt>RTPTranslator</tt> associated with this strategy. */ private RTPTranslator translator; @Override public RTCPPacket[] makeReports() { if (rtcpTransmitter == null) throw new IllegalStateException("rtcpTransmitter is not set"); RTPTranslator t = this.translator; if (t == null || !(t instanceof RTPTranslatorImpl)) return new RTCPPacket[0]; // Use the SSRC of the bridge that is announced and the endpoints won't // drop the packet. int localSSRC = (int) ((RTPTranslatorImpl)t).getLocalSSRC(null); Vector<RTCPPacket> packets = new Vector<RTCPPacket>(); long time = System.currentTimeMillis(); RTCPReportBlock reports[] = makeReceiverReports(time); RTCPReportBlock firstrep[] = reports; // If the number of sources for which reception statistics are being // reported exceeds 31, the number that will fit into one SR or RR // packet, then additional RR packets SHOULD follow the initial report // packet. if (reports.length > 31) { firstrep = new RTCPReportBlock[31]; System.arraycopy(reports, 0, firstrep, 0, 31); } packets.addElement(new RTCPRRPacket(localSSRC, firstrep)); if (firstrep != reports) { for (int offset = 31; offset < reports.length; offset += 31) { if (reports.length - offset < 31) firstrep = new RTCPReportBlock[reports.length - offset]; System.arraycopy(reports, offset, firstrep, 0, firstrep.length); RTCPRRPacket rrp = new RTCPRRPacket(localSSRC, firstrep); packets.addElement(rrp); } } // Include REMB. if (this.feedbackCacheProcessor == null) { this.feedbackCacheProcessor = new FeedbackCacheProcessor(feedbackCache); // TODO(gp) make percentile configurable. this.feedbackCacheProcessor.setPercentile(70); } RTCPPacket[] bestReceiverFeedback = feedbackCacheProcessor.makeReports( localSSRC); if (bestReceiverFeedback != null && bestReceiverFeedback.length != 0) { for (RTCPPacket packet : bestReceiverFeedback) { if (packet.type == RTCPPacketType.PSFB && packet instanceof RTCPFBPacket && ((RTCPFBPacket)packet).fmt == RTCPPSFBFormat.REMB) { packets.add(packet); } } } // TODO(gp) for RTCP compound packets MUST contain an SDES packet. // Copy into an array and return. RTCPPacket[] res = new RTCPPacket[packets.size()]; packets.copyInto(res); return res; } private RTCPReportBlock[] makeReceiverReports(long time) { Vector<RTCPReportBlock> reports = new Vector<RTCPReportBlock>(); // Make receiver reports for all known SSRCs. for (Enumeration<SSRCInfo> elements = rtcpTransmitter.cache.cache.elements(); elements.hasMoreElements();) { SSRCInfo info = elements.nextElement(); if (!info.ours && info.sender) { int ssrc = info.ssrc; long lastseq = info.maxseq + info.cycles; int jitter = (int) info.jitter; long lsr = (int) ((info.lastSRntptimestamp & 0x0000ffffffff0000L) >> 16); long dlsr = (int) ((time - info.lastSRreceiptTime) * 65.536000000000001D); int packetslost = (int) (((lastseq - info.baseseq) + 1L) - info.received); if (packetslost < 0) packetslost = 0; double frac = (double) (packetslost - info.prevlost) / (double) (lastseq - info.prevmaxseq); if (frac < 0.0D) frac = 0.0D; int fractionlost =(int) (frac * 256D); RTCPReportBlock receiverReport = new RTCPReportBlock( ssrc, fractionlost, packetslost, lastseq, jitter, lsr, dlsr ); info.prevmaxseq = (int) lastseq; info.prevlost = packetslost; reports.addElement(receiverReport); } } // Copy into an array and return. RTCPReportBlock res[] = new RTCPReportBlock[reports.size()]; reports.copyInto(res); return res; } @Override public void reset() { /* Nothing to do here */ } @Override public void setRTCPTransmitter(RTCPTransmitter rtcpTransmitter) { this.rtcpTransmitter = rtcpTransmitter; } @Override public RTCPPacketTransformer getRTCPPacketTransformer() { return this; } @Override public RTCPReportBuilder getRTCPReportBuilder() { return this; } @Override public void setRTPTranslator(RTPTranslator translator) { this.translator = translator; } @Override public RTCPCompoundPacket transformRTCPPacket( RTCPCompoundPacket inPacket) { // Removes receiver report blocks from RRs and SRs and kills REMBs. if (inPacket == null || inPacket.packets == null || inPacket.packets.length == 0) { return inPacket; } Vector<RTCPPacket> outPackets = new Vector<RTCPPacket>(inPacket.packets.length); // These are the data that are of interest to us : RR report blocks and // REMBs. We'll also need the SSRC of the RTCP report sender. RTCPReportBlock[] reports = null; RTCPREMBPacket remb = null; Integer ssrc = 0; // Modify the incoming RTCP packet and/or update the // <tt>feedbackCache</tt>. for (RTCPPacket p : inPacket.packets) { switch (p.type) { case RTCPPacketType.RR: // Grab the receiver report blocks to put them into the // cache after the loop is done and mute the RR. RTCPRRPacket rr = (RTCPRRPacket) p; reports = rr.reports; ssrc = Integer.valueOf(rr.ssrc); break; case RTCPPacketType.SR: // Grab the receiver report blocks to put them into the // cache after the loop is done; mute the receiver report // blocks. RTCPSRPacket sr = (RTCPSRPacket) p; outPackets.add(sr); reports = sr.reports; ssrc = Integer.valueOf(sr.ssrc); sr.reports = new RTCPReportBlock[0]; break; case RTCPPacketType.PSFB: RTCPFBPacket psfb = (RTCPFBPacket) p; switch (psfb.fmt) { case RTCPPSFBFormat.REMB: // NOT adding the REMB in the outPacket as we mute // REMBs from the peers. // // We put it into the feedback cache instead. remb = (RTCPREMBPacket) p; ssrc = Integer.valueOf((int) remb.senderSSRC); break; default: // Pass through everything else, like PLIs and NACKs outPackets.add(psfb); break; } break; default: // Pass through everything else, like PLIs and NACKs outPackets.add(p); break; } } feedbackCache.update(ssrc, reports, remb); RTCPPacket[] outarr = new RTCPPacket[outPackets.size()]; outPackets.copyInto(outarr); RTCPCompoundPacket outPacket = new RTCPCompoundPacket(outarr); return outPacket; } }
Changes BasicRTCPTerminationStrategy fields visibility and adds a few comments.
src/org/jitsi/impl/neomedia/rtcp/termination/strategies/BasicRTCPTerminationStrategy.java
Changes BasicRTCPTerminationStrategy fields visibility and adds a few comments.
<ide><path>rc/org/jitsi/impl/neomedia/rtcp/termination/strategies/BasicRTCPTerminationStrategy.java <ide> * A cache of media receiver feedback. It contains both receiver report <ide> * blocks and REMB packets. <ide> */ <del> private final FeedbackCache feedbackCache; <add> protected final FeedbackCache feedbackCache; <ide> <ide> /** <ide> * The cache processor that will be making the RTCP reports coming from <ide> /** <ide> * The <tt>RTPTranslator</tt> associated with this strategy. <ide> */ <del> private RTPTranslator translator; <add> protected RTPTranslator translator; <ide> <ide> @Override <ide> public RTCPPacket[] makeReports() <ide> } <ide> <ide> // Include REMB. <add> <add> // TODO(gp) build REMB packets from scratch. <ide> if (this.feedbackCacheProcessor == null) <ide> { <ide> this.feedbackCacheProcessor <ide> this.translator = translator; <ide> } <ide> <add> /** <add> * 1. Removes receiver report blocks from RRs and SRs and kills REMBs. <add> * 2. Updates the receiver feedback cache. <add> * <add> * @param inPacket <add> * @return <add> */ <ide> @Override <ide> public RTCPCompoundPacket transformRTCPPacket( <ide> RTCPCompoundPacket inPacket) <ide> { <del> // Removes receiver report blocks from RRs and SRs and kills REMBs. <del> <ide> if (inPacket == null <ide> || inPacket.packets == null || inPacket.packets.length == 0) <ide> { <ide> return inPacket; <ide> } <ide> <del> Vector<RTCPPacket> outPackets = new Vector<RTCPPacket>(inPacket.packets.length); <add> Vector<RTCPPacket> outPackets = new Vector<RTCPPacket>( <add> inPacket.packets.length); <ide> <ide> // These are the data that are of interest to us : RR report blocks and <ide> // REMBs. We'll also need the SSRC of the RTCP report sender.
Java
apache-2.0
b8e00215859703a00945b154bb049f4f68455ace
0
codybum/Cresco-Container-Plugin
import com.google.auto.service.AutoService; import com.researchworx.cresco.library.plugin.core.CPlugin; import java.util.ArrayList; import java.util.List; @AutoService(CPlugin.class) public class Plugin extends CPlugin { public DockerEngine de; private PerfMonitor perfMonitor; @Override public void setExecutor() { setExec(new Executor(this)); } public void start() { de = new DockerEngine(); String containerImage = this.config.getStringParam("container_image"); if(containerImage == null) { logger.error("start() Container must privite image name!"); } else { List<String> envList = parseEParams(this.config.getStringParam("e_params")); if(envList != null) { for (String ep : envList) { logger.info("e_param: " + ep); } } List<String> portList = parsePParams(this.config.getStringParam("p_params")); if(portList != null) { for (String p : portList) { logger.info("p_param: " + p); } } String container_id = de.createContainer(containerImage,envList,portList); de.startContainer(container_id); logger.info("Container initialized"); perfMonitor = new PerfMonitor(this, de, container_id); perfMonitor.start(); logger.info("Container performance monitoring initialized"); setExec(new Executor(this)); } } private List<String> parsePParams(String paramString) { List<String> params = null; try { if(paramString != null) { params = new ArrayList<>(); if(paramString.contains(":")){ for(String param : paramString.split(":")) { params.add(param); } } else { params.add(paramString); } } } catch(Exception ex) { logger.error("parseParams " + ex.getMessage()); } return params; } private List<String> parseEParams(String paramString) { List<String> params = null; try { if(paramString != null) { params = new ArrayList<>(); if(paramString.contains(":")){ for(String param : paramString.split(":")) { String paramVal = this.config.getStringParam(param); if(paramVal != null) { params.add(param + "=" + paramVal); } } } else { String paramVal = this.config.getStringParam(paramString); if(paramVal != null) { params.add(paramString + "=" + paramVal); } } } } catch(Exception ex) { logger.error("parseParams " + ex.getMessage()); } return params; } @Override public void cleanUp() { perfMonitor.stop(); de.shutdown(); } }
src/main/java/Plugin.java
import com.google.auto.service.AutoService; import com.researchworx.cresco.library.plugin.core.CPlugin; import java.util.ArrayList; import java.util.List; @AutoService(CPlugin.class) public class Plugin extends CPlugin { public DockerEngine de; private PerfMonitor perfMonitor; @Override public void setExecutor() { setExec(new Executor(this)); } public void start() { de = new DockerEngine(); String containerImage = this.config.getStringParam("container_image"); if(containerImage == null) { logger.error("start() Container must privite image name!"); } else { List<String> envList = parseEParams(this.config.getStringParam("e_params")); List<String> portList = parsePParams(this.config.getStringParam("p_params")); String container_id = de.createContainer(containerImage,envList,portList); de.startContainer(container_id); logger.info("Container initialized"); perfMonitor = new PerfMonitor(this, de, container_id); perfMonitor.start(); logger.info("Container performance monitoring initialized"); setExec(new Executor(this)); } } private List<String> parsePParams(String paramString) { List<String> params = null; try { if(paramString != null) { params = new ArrayList<>(); if(paramString.contains(",")){ for(String param : paramString.split(",")) { params.add(param); } } else { params.add(paramString); } } } catch(Exception ex) { logger.error("parseParams " + ex.getMessage()); } return params; } private List<String> parseEParams(String paramString) { List<String> params = null; try { if(paramString != null) { params = new ArrayList<>(); if(paramString.contains(",")){ for(String param : paramString.split(",")) { String paramVal = this.config.getStringParam(param); if(paramVal != null) { params.add(param + "=" + paramVal); } } } else { String paramVal = this.config.getStringParam(paramString); if(paramVal != null) { params.add(paramString + "=" + paramVal); } } } } catch(Exception ex) { logger.error("parseParams " + ex.getMessage()); } return params; } @Override public void cleanUp() { perfMonitor.stop(); de.shutdown(); } }
rolled back docker-client version due to errors with docker 13.0
src/main/java/Plugin.java
rolled back docker-client version due to errors with docker 13.0
<ide><path>rc/main/java/Plugin.java <ide> } <ide> else { <ide> List<String> envList = parseEParams(this.config.getStringParam("e_params")); <add> if(envList != null) { <add> for (String ep : envList) { <add> logger.info("e_param: " + ep); <add> } <add> } <ide> List<String> portList = parsePParams(this.config.getStringParam("p_params")); <add> if(portList != null) { <add> for (String p : portList) { <add> logger.info("p_param: " + p); <add> } <add> } <ide> String container_id = de.createContainer(containerImage,envList,portList); <ide> de.startContainer(container_id); <ide> logger.info("Container initialized"); <ide> try { <ide> if(paramString != null) { <ide> params = new ArrayList<>(); <del> if(paramString.contains(",")){ <del> for(String param : paramString.split(",")) { <add> if(paramString.contains(":")){ <add> for(String param : paramString.split(":")) { <ide> params.add(param); <ide> } <ide> } <ide> try { <ide> if(paramString != null) { <ide> params = new ArrayList<>(); <del> if(paramString.contains(",")){ <del> for(String param : paramString.split(",")) { <add> if(paramString.contains(":")){ <add> for(String param : paramString.split(":")) { <ide> String paramVal = this.config.getStringParam(param); <ide> if(paramVal != null) { <ide> params.add(param + "=" + paramVal);
Java
apache-2.0
cec36b4dbb3671aa39cb4f2dcf7cb11ee2e5e5e5
0
ferstl/depgraph-maven-plugin
/* * Copyright (c) 2014 - 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ferstl.depgraph.dependency; import java.util.Arrays; import java.util.EnumSet; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import com.github.ferstl.depgraph.graph.GraphBuilder; import static com.github.ferstl.depgraph.graph.GraphBuilderMatcher.hasNodesAndEdges; import static java.util.EnumSet.allOf; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GraphBuildingVisitorTest { private GraphBuilder<DependencyNode> graphBuilder; private GraphBuildingVisitor visitor; private ArtifactFilter globalFilter; private ArtifactFilter targetFilter; private EnumSet<NodeResolution> includedResolutions; @Before public void before() { this.graphBuilder = new GraphBuilder<>(); this.globalFilter = mock(ArtifactFilter.class); when(this.globalFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(true); // this is the same as an empty list of target dependencies this.targetFilter = mock(ArtifactFilter.class); when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(true); this.includedResolutions = allOf(NodeResolution.class); this.visitor = new GraphBuildingVisitor(this.graphBuilder, this.globalFilter, this.targetFilter, this.includedResolutions); } /** * . * <pre> * parent * - child * </pre> */ @Test public void parentAndChild() { org.apache.maven.shared.dependency.graph.DependencyNode child = createGraphNode("child"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child)); assertTrue(this.visitor.endVisit(child)); assertTrue(this.visitor.endVisit(parent)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child:jar:version:compile\"[label=\"groupId:child:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child:jar:version:compile\""})); } /** * . * <pre> * parent * - child1 * - child2(ignored) * </pre> */ @Test public void ignoredNode() { org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1"); org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2); when(this.globalFilter.include(child2.getArtifact())).thenReturn(false); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child1)); assertTrue(this.visitor.endVisit(child1)); // Don't process any further children of child2 assertFalse(this.visitor.visit(child2)); assertFalse(this.visitor.endVisit(child2)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child1:jar:version:compile\"[label=\"groupId:child1:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child1:jar:version:compile\""})); } /** * . * <pre> * parent * - child1 * - child2 (target dependency) * </pre> */ @Test public void targetDepNode() { org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1"); org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2); when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(false); when(this.targetFilter.include(child2.getArtifact())).thenReturn(true); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child1)); assertTrue(this.visitor.endVisit(child1)); assertTrue(this.visitor.visit(child2)); assertTrue(this.visitor.endVisit(child2)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child2:jar:version:compile\"[label=\"groupId:child2:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child2:jar:version:compile\""})); } /** * . * <pre> * parent * - child1 * - child4 (target dependency) * - child2 * - child3 (target dependency) * - child4 (target dependency) * </pre> */ @Test public void multiTargetDepNode() { org.apache.maven.shared.dependency.graph.DependencyNode child4 = createGraphNode("child4"); org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1", child4); org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); org.apache.maven.shared.dependency.graph.DependencyNode child3 = createGraphNode("child3", child4); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2, child3); when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(false); when(this.targetFilter.include(child3.getArtifact())).thenReturn(true); when(this.targetFilter.include(child4.getArtifact())).thenReturn(true); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child1)); assertTrue(this.visitor.visit(child4)); assertTrue(this.visitor.endVisit(child4)); assertTrue(this.visitor.endVisit(child1)); assertTrue(this.visitor.visit(child2)); assertTrue(this.visitor.endVisit(child2)); assertTrue(this.visitor.visit(child3)); assertTrue(this.visitor.visit(child4)); assertTrue(this.visitor.endVisit(child4)); assertTrue(this.visitor.endVisit(child3)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child1:jar:version:compile\"[label=\"groupId:child1:jar:version:compile\"]", "\"groupId:child3:jar:version:compile\"[label=\"groupId:child3:jar:version:compile\"]", "\"groupId:child4:jar:version:compile\"[label=\"groupId:child4:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child1:jar:version:compile\"", "\"groupId:parent:jar:version:compile\" -> \"groupId:child3:jar:version:compile\"", "\"groupId:child1:jar:version:compile\" -> \"groupId:child4:jar:version:compile\"", "\"groupId:child3:jar:version:compile\" -> \"groupId:child4:jar:version:compile\"" })); } @Test public void defaultArtifactFilter() { this.visitor = new GraphBuildingVisitor(this.graphBuilder, this.targetFilter); // Use other test (I know this is ugly...) parentAndChild(); } private static org.apache.maven.shared.dependency.graph.DependencyNode createGraphNode(String artifactId, org.apache.maven.shared.dependency.graph.DependencyNode... children) { org.apache.maven.shared.dependency.graph.DependencyNode node = mock(org.apache.maven.shared.dependency.graph.DependencyNode.class); when(node.getArtifact()).thenReturn(createArtifact(artifactId)); when(node.getChildren()).thenReturn(Arrays.asList(children)); return node; } private static Artifact createArtifact(String artifactId) { return new DefaultArtifact("groupId", artifactId, "version", "compile", "jar", "", null); } }
src/test/java/com/github/ferstl/depgraph/dependency/GraphBuildingVisitorTest.java
/* * Copyright (c) 2014 - 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.ferstl.depgraph.dependency; import java.util.Arrays; import java.util.EnumSet; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.resolver.filter.ArtifactFilter; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import com.github.ferstl.depgraph.graph.GraphBuilder; import static com.github.ferstl.depgraph.graph.GraphBuilderMatcher.hasNodesAndEdges; import static java.util.EnumSet.allOf; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class GraphBuildingVisitorTest { private GraphBuilder<DependencyNode> graphBuilder; private GraphBuildingVisitor visitor; private ArtifactFilter globalFilter; private ArtifactFilter targetFilter; private EnumSet<NodeResolution> includedResolutions; @Before public void before() { this.graphBuilder = new GraphBuilder<>(); this.globalFilter = mock(ArtifactFilter.class); when(this.globalFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(true); // this is the same as an empty list of target dependencies this.targetFilter = mock(ArtifactFilter.class); when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(true); this.includedResolutions = allOf(NodeResolution.class); this.visitor = new GraphBuildingVisitor(this.graphBuilder, this.globalFilter, this.targetFilter, this.includedResolutions); } /** * . * <pre> * parent * - child * </pre> */ @Test public void parentAndChild() { org.apache.maven.shared.dependency.graph.DependencyNode child = createGraphNode("child"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child)); assertTrue(this.visitor.endVisit(child)); assertTrue(this.visitor.endVisit(parent)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child:jar:version:compile\"[label=\"groupId:child:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child:jar:version:compile\""})); } /** * . * <pre> * parent * - child1 * - child2(ignored) * </pre> */ @Test public void ignoredNode() { org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1"); org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2); when(this.globalFilter.include(child2.getArtifact())).thenReturn(false); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child1)); assertTrue(this.visitor.endVisit(child1)); // Don't process any further children of child2 assertFalse(this.visitor.visit(child2)); assertFalse(this.visitor.endVisit(child2)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child1:jar:version:compile\"[label=\"groupId:child1:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child1:jar:version:compile\""})); } /** * . * <pre> * parent * - child1 * - child2 (target dependency) * </pre> */ @Test public void targetDepNode() { org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1"); org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2); when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(false); when(this.targetFilter.include(child2.getArtifact())).thenReturn(true); assertTrue(this.visitor.visit(parent)); assertTrue(this.visitor.visit(child1)); assertTrue(this.visitor.endVisit(child1)); assertTrue(this.visitor.visit(child2)); assertTrue(this.visitor.endVisit(child2)); assertThat(this.graphBuilder, hasNodesAndEdges( new String[]{ "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", "\"groupId:child2:jar:version:compile\"[label=\"groupId:child2:jar:version:compile\"]"}, new String[]{ "\"groupId:parent:jar:version:compile\" -> \"groupId:child2:jar:version:compile\""})); } @Test public void defaultArtifactFilter() { this.visitor = new GraphBuildingVisitor(this.graphBuilder, this.targetFilter); // Use other test (I know this is ugly...) parentAndChild(); } private static org.apache.maven.shared.dependency.graph.DependencyNode createGraphNode(String artifactId, org.apache.maven.shared.dependency.graph.DependencyNode... children) { org.apache.maven.shared.dependency.graph.DependencyNode node = mock(org.apache.maven.shared.dependency.graph.DependencyNode.class); when(node.getArtifact()).thenReturn(createArtifact(artifactId)); when(node.getChildren()).thenReturn(Arrays.asList(children)); return node; } private static Artifact createArtifact(String artifactId) { return new DefaultArtifact("groupId", artifactId, "version", "compile", "jar", "", null); } }
#35: Add test for multiple target dependency nodes
src/test/java/com/github/ferstl/depgraph/dependency/GraphBuildingVisitorTest.java
#35: Add test for multiple target dependency nodes
<ide><path>rc/test/java/com/github/ferstl/depgraph/dependency/GraphBuildingVisitorTest.java <ide> new String[]{ <ide> "\"groupId:parent:jar:version:compile\" -> \"groupId:child2:jar:version:compile\""})); <ide> } <del> <add> <add> /** <add> * . <add> * <pre> <add> * parent <add> * - child1 <add> * - child4 (target dependency) <add> * - child2 <add> * - child3 (target dependency) <add> * - child4 (target dependency) <add> * </pre> <add> */ <add> @Test <add> public void multiTargetDepNode() { <add> org.apache.maven.shared.dependency.graph.DependencyNode child4 = createGraphNode("child4"); <add> org.apache.maven.shared.dependency.graph.DependencyNode child1 = createGraphNode("child1", child4); <add> org.apache.maven.shared.dependency.graph.DependencyNode child2 = createGraphNode("child2"); <add> org.apache.maven.shared.dependency.graph.DependencyNode child3 = createGraphNode("child3", child4); <add> org.apache.maven.shared.dependency.graph.DependencyNode parent = createGraphNode("parent", child1, child2, child3); <add> <add> when(this.targetFilter.include(ArgumentMatchers.<Artifact>any())).thenReturn(false); <add> when(this.targetFilter.include(child3.getArtifact())).thenReturn(true); <add> when(this.targetFilter.include(child4.getArtifact())).thenReturn(true); <add> <add> assertTrue(this.visitor.visit(parent)); <add> <add> assertTrue(this.visitor.visit(child1)); <add> assertTrue(this.visitor.visit(child4)); <add> assertTrue(this.visitor.endVisit(child4)); <add> assertTrue(this.visitor.endVisit(child1)); <add> <add> assertTrue(this.visitor.visit(child2)); <add> assertTrue(this.visitor.endVisit(child2)); <add> <add> assertTrue(this.visitor.visit(child3)); <add> assertTrue(this.visitor.visit(child4)); <add> assertTrue(this.visitor.endVisit(child4)); <add> assertTrue(this.visitor.endVisit(child3)); <add> <add> assertThat(this.graphBuilder, hasNodesAndEdges( <add> new String[]{ <add> "\"groupId:parent:jar:version:compile\"[label=\"groupId:parent:jar:version:compile\"]", <add> "\"groupId:child1:jar:version:compile\"[label=\"groupId:child1:jar:version:compile\"]", <add> "\"groupId:child3:jar:version:compile\"[label=\"groupId:child3:jar:version:compile\"]", <add> "\"groupId:child4:jar:version:compile\"[label=\"groupId:child4:jar:version:compile\"]"}, <add> new String[]{ <add> "\"groupId:parent:jar:version:compile\" -> \"groupId:child1:jar:version:compile\"", <add> "\"groupId:parent:jar:version:compile\" -> \"groupId:child3:jar:version:compile\"", <add> "\"groupId:child1:jar:version:compile\" -> \"groupId:child4:jar:version:compile\"", <add> "\"groupId:child3:jar:version:compile\" -> \"groupId:child4:jar:version:compile\"" <add> <add> <add> })); <add> } <add> <add> <ide> @Test <ide> public void defaultArtifactFilter() { <ide> this.visitor = new GraphBuildingVisitor(this.graphBuilder, this.targetFilter);
Java
apache-2.0
bdbe764f6d5b671e1e6de0f01e88be87e6938698
0
TheNightForum/Path-to-Mani,BurntGameProductions/Path-to-Mani,BurntGameProductions/Path-to-Mani,BurntGameProductions/Path-to-Mani,TheNightForum/Path-to-Mani,TheNightForum/Path-to-Mani
/* * Copyright 2016 BurntGameProductions * * 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.pathtomani.entities.planet; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; import com.pathtomani.entities.item.TradeConfig; import com.pathtomani.gfx.TextureManager; import com.pathtomani.common.ManiMath; import com.pathtomani.managers.files.FileManager; import com.pathtomani.managers.files.HullConfigManager; import com.pathtomani.game.ShipConfig; import com.pathtomani.game.chunk.SpaceEnvConfig; import com.pathtomani.entities.item.ItemManager; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class SysConfigs { private final Map<String, SysConfig> myConfigs; private final Map<String, SysConfig> myHardConfigs; private final Map<String, SysConfig> myBeltConfigs; private final Map<String, SysConfig> myHardBeltConfigs; public SysConfigs(TextureManager textureManager, HullConfigManager hullConfigs, ItemManager itemManager) { myConfigs = new HashMap<String, SysConfig>(); myHardConfigs = new HashMap<String, SysConfig>(); myBeltConfigs = new HashMap<String, SysConfig>(); myHardBeltConfigs = new HashMap<String, SysConfig>(); load(textureManager, hullConfigs, false, "systems.json", itemManager); load(textureManager, hullConfigs, true, "asteroidBelts.json", itemManager); } private void load(TextureManager textureManager, HullConfigManager hullConfigs, boolean belts, String configName, ItemManager itemManager) { JsonReader r = new JsonReader(); FileHandle configFile = FileManager.getInstance().getConfigDirectory().child(configName); JsonValue parsed = r.parse(configFile); for (JsonValue sh : parsed) { ArrayList<ShipConfig> tempEnemies = ShipConfig.loadList(sh.get("temporaryEnemies"), hullConfigs, itemManager); ArrayList<ShipConfig> innerTempEnemies = ShipConfig.loadList(sh.get("innerTemporaryEnemies"), hullConfigs, itemManager); SpaceEnvConfig envConfig = new SpaceEnvConfig(sh.get("environment"), textureManager, configFile); ArrayList<ShipConfig> constEnemies = null; ArrayList<ShipConfig> constAllies = null; if (!belts) { constEnemies = ShipConfig.loadList(sh.get("constantEnemies"), hullConfigs, itemManager); constAllies = ShipConfig.loadList(sh.get("constantAllies"), hullConfigs, itemManager); } TradeConfig tradeConfig = TradeConfig.load(itemManager, sh.get("trading"), hullConfigs); boolean hard = sh.getBoolean("hard", false); SysConfig c = new SysConfig(sh.name, tempEnemies, envConfig, constEnemies, constAllies, tradeConfig, innerTempEnemies, hard); Map<String, SysConfig> configs = belts ? hard ? myHardBeltConfigs : myBeltConfigs : hard ? myHardConfigs : myConfigs; configs.put(sh.name, c); } } public SysConfig getRandomBelt(boolean hard) { Map<String, SysConfig> config = hard ? myHardBeltConfigs : myBeltConfigs; return ManiMath.elemRnd(new ArrayList<SysConfig>(config.values())); } public SysConfig getConfig(String name) { SysConfig res = myConfigs.get(name); if (res != null) return res; return myHardConfigs.get(name); } public SysConfig getRandomCfg(boolean hard) { Map<String, SysConfig> config = hard ? myHardConfigs : myConfigs; return ManiMath.elemRnd(new ArrayList<SysConfig>(config.values())); } public void addAllConfigs(ArrayList<ShipConfig> l) { for (SysConfig sc : myConfigs.values()) { l.addAll(sc.constAllies); l.addAll(sc.constEnemies); l.addAll(sc.tempEnemies); l.addAll(sc.innerTempEnemies); } for (SysConfig sc : myHardConfigs.values()) { l.addAll(sc.constAllies); l.addAll(sc.constEnemies); l.addAll(sc.tempEnemies); l.addAll(sc.innerTempEnemies); } for (SysConfig sc : myBeltConfigs.values()) { l.addAll(sc.tempEnemies); } for (SysConfig sc : myHardBeltConfigs.values()) { l.addAll(sc.tempEnemies); } } }
main/src/com/pathtomani/entities/planet/SysConfigs.java
/* * Copyright 2016 BurntGameProductions * * 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.pathtomani.entities.planet; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.JsonReader; import com.badlogic.gdx.utils.JsonValue; import com.pathtomani.entities.item.TradeConfig; import com.pathtomani.gfx.TextureManager; import com.pathtomani.common.ManiMath; import com.pathtomani.files.FileManager; import com.pathtomani.files.HullConfigManager; import com.pathtomani.game.ShipConfig; import com.pathtomani.game.chunk.SpaceEnvConfig; import com.pathtomani.entities.item.ItemManager; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class SysConfigs { private final Map<String, SysConfig> myConfigs; private final Map<String, SysConfig> myHardConfigs; private final Map<String, SysConfig> myBeltConfigs; private final Map<String, SysConfig> myHardBeltConfigs; public SysConfigs(TextureManager textureManager, HullConfigManager hullConfigs, ItemManager itemManager) { myConfigs = new HashMap<String, SysConfig>(); myHardConfigs = new HashMap<String, SysConfig>(); myBeltConfigs = new HashMap<String, SysConfig>(); myHardBeltConfigs = new HashMap<String, SysConfig>(); load(textureManager, hullConfigs, false, "systems.json", itemManager); load(textureManager, hullConfigs, true, "asteroidBelts.json", itemManager); } private void load(TextureManager textureManager, HullConfigManager hullConfigs, boolean belts, String configName, ItemManager itemManager) { JsonReader r = new JsonReader(); FileHandle configFile = FileManager.getInstance().getConfigDirectory().child(configName); JsonValue parsed = r.parse(configFile); for (JsonValue sh : parsed) { ArrayList<ShipConfig> tempEnemies = ShipConfig.loadList(sh.get("temporaryEnemies"), hullConfigs, itemManager); ArrayList<ShipConfig> innerTempEnemies = ShipConfig.loadList(sh.get("innerTemporaryEnemies"), hullConfigs, itemManager); SpaceEnvConfig envConfig = new SpaceEnvConfig(sh.get("environment"), textureManager, configFile); ArrayList<ShipConfig> constEnemies = null; ArrayList<ShipConfig> constAllies = null; if (!belts) { constEnemies = ShipConfig.loadList(sh.get("constantEnemies"), hullConfigs, itemManager); constAllies = ShipConfig.loadList(sh.get("constantAllies"), hullConfigs, itemManager); } TradeConfig tradeConfig = TradeConfig.load(itemManager, sh.get("trading"), hullConfigs); boolean hard = sh.getBoolean("hard", false); SysConfig c = new SysConfig(sh.name, tempEnemies, envConfig, constEnemies, constAllies, tradeConfig, innerTempEnemies, hard); Map<String, SysConfig> configs = belts ? hard ? myHardBeltConfigs : myBeltConfigs : hard ? myHardConfigs : myConfigs; configs.put(sh.name, c); } } public SysConfig getRandomBelt(boolean hard) { Map<String, SysConfig> config = hard ? myHardBeltConfigs : myBeltConfigs; return ManiMath.elemRnd(new ArrayList<SysConfig>(config.values())); } public SysConfig getConfig(String name) { SysConfig res = myConfigs.get(name); if (res != null) return res; return myHardConfigs.get(name); } public SysConfig getRandomCfg(boolean hard) { Map<String, SysConfig> config = hard ? myHardConfigs : myConfigs; return ManiMath.elemRnd(new ArrayList<SysConfig>(config.values())); } public void addAllConfigs(ArrayList<ShipConfig> l) { for (SysConfig sc : myConfigs.values()) { l.addAll(sc.constAllies); l.addAll(sc.constEnemies); l.addAll(sc.tempEnemies); l.addAll(sc.innerTempEnemies); } for (SysConfig sc : myHardConfigs.values()) { l.addAll(sc.constAllies); l.addAll(sc.constEnemies); l.addAll(sc.tempEnemies); l.addAll(sc.innerTempEnemies); } for (SysConfig sc : myBeltConfigs.values()) { l.addAll(sc.tempEnemies); } for (SysConfig sc : myHardBeltConfigs.values()) { l.addAll(sc.tempEnemies); } } }
Moving files to Managers.
main/src/com/pathtomani/entities/planet/SysConfigs.java
Moving files to Managers.
<ide><path>ain/src/com/pathtomani/entities/planet/SysConfigs.java <ide> import com.pathtomani.entities.item.TradeConfig; <ide> import com.pathtomani.gfx.TextureManager; <ide> import com.pathtomani.common.ManiMath; <del>import com.pathtomani.files.FileManager; <del>import com.pathtomani.files.HullConfigManager; <add>import com.pathtomani.managers.files.FileManager; <add>import com.pathtomani.managers.files.HullConfigManager; <ide> import com.pathtomani.game.ShipConfig; <ide> import com.pathtomani.game.chunk.SpaceEnvConfig; <ide> import com.pathtomani.entities.item.ItemManager;
Java
epl-1.0
0498f0653d5a405d888317734e60d2d78c247641
0
rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.factory; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Locale; import org.eclipse.birt.chart.computation.IConstants; import org.eclipse.birt.chart.computation.withaxes.LegendItemRenderingHints; import org.eclipse.birt.chart.computation.withaxes.PlotWith2DAxes; import org.eclipse.birt.chart.computation.withoutaxes.PlotWithoutAxes; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IDisplayServer; import org.eclipse.birt.chart.exception.GenerationException; import org.eclipse.birt.chart.exception.OverlapException; import org.eclipse.birt.chart.exception.RenderingException; import org.eclipse.birt.chart.exception.ScriptException; import org.eclipse.birt.chart.exception.UnsupportedFeatureException; import org.eclipse.birt.chart.log.DefaultLoggerImpl; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.ScriptHandler; import org.eclipse.birt.chart.model.attribute.Anchor; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.Insets; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.birt.chart.model.attribute.Size; import org.eclipse.birt.chart.model.attribute.impl.BoundsImpl; import org.eclipse.birt.chart.model.layout.Block; import org.eclipse.birt.chart.model.layout.LayoutManager; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.render.BaseRenderer; import org.eclipse.emf.ecore.util.EcoreUtil; import org.mozilla.javascript.Scriptable; /** * This class provides a factory entry point into building a chart for a given model. It is implemented as a singleton * and does not maintain any state information hence allowing multi-threaded requests for a single Generator instance. * * @author Actuate Corporation */ public final class Generator { /** * */ private static final int UNDEFINED = IConstants.UNDEFINED; /** * */ static final int WITH_AXES = 1; /** * */ static final int WITHOUT_AXES = 2; /** * */ private static final LegendItemRenderingHints[] EMPTY_LIRHA = new LegendItemRenderingHints[0]; /** * The internal singleton Generator reference */ private static Generator g = null; /** * A private constructor */ private Generator() { } /** * * @return A singleton instance for the Generator. */ public static synchronized final Generator instance() { if (g == null) { g = new Generator(); } return g; } /** * This method builds the chart (offscreen) using the provided display server * * @param xs * @param cmDesignTime * @param scParent * @param bo * @param lo * @return * @throws GenerationException */ public final GeneratedChartState build(IDisplayServer xs, Chart cmDesignTime, Scriptable scParent, Bounds bo, Locale lo) throws GenerationException { if (xs == null || cmDesignTime == null || bo == null) { throw new GenerationException("Illegal 'null' value passed as an argument to build a chart"); } if (cmDesignTime.getDimension() == ChartDimension.THREE_DIMENSIONAL_LITERAL) { throw new GenerationException(new UnsupportedFeatureException("3D charts are not yet supported")); } Chart cmRunTime = (Chart) EcoreUtil.copy(cmDesignTime); if (lo == null) { lo = Locale.getDefault(); } final String sScriptContent = cmRunTime.getScript(); ScriptHandler sh = cmDesignTime.getScriptHandler(); if (sh == null && sScriptContent != null) // NOT PREVIOUSLY DEFINED BY REPORTITEM ADAPTER { sh = new ScriptHandler(); try { sh.init(scParent); sh.setRunTimeModel(cmRunTime); cmRunTime.setScriptHandler(sh); sh.register(sScriptContent); } catch (ScriptException sx ) { throw new GenerationException(sx); } } else if (sh != null) // COPY SCRIPTS FROM DESIGNTIME TO RUNTIME INSTANCE { cmRunTime.setScriptHandler(sh); } // SETUP THE COMPUTATIONS ScriptHandler.callFunction(sh, ScriptHandler.START_GENERATION, cmRunTime); int iChartType = UNDEFINED; Object oComputations = null; if (cmRunTime instanceof ChartWithAxes) { iChartType = WITH_AXES; oComputations = new PlotWith2DAxes(xs, (ChartWithAxes) cmRunTime, lo); } else if (cmRunTime instanceof ChartWithoutAxes) { iChartType = WITHOUT_AXES; oComputations = new PlotWithoutAxes(xs, (ChartWithoutAxes) cmRunTime, lo); } if (oComputations == null) { throw new GenerationException("Unable to compute chart defined by model [" + cmRunTime + "]"); } // OBTAIN THE RENDERERS final ILogger il = DefaultLoggerImpl.instance(); final LinkedHashMap lhmRenderers = new LinkedHashMap(); BaseRenderer[] brna = null; try { brna = BaseRenderer.instances(cmRunTime, oComputations); for (int i = 0; i < brna.length; i++) { lhmRenderers.put(brna[i].getSeries(), new LegendItemRenderingHints(brna[i], BoundsImpl.create(0, 0, 0, 0))); } } catch (Exception ex ) { ex.printStackTrace(); throw new GenerationException(ex); } // PERFORM THE BLOCKS' LAYOUT Block bl = cmRunTime.getBlock(); final LayoutManager lm = new LayoutManager(bl); ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_LAYOUT, cmRunTime); try { lm.doLayout_tmp(xs, cmRunTime, bo); } catch (OverlapException oex ) { throw new GenerationException(oex); } ScriptHandler.callFunction(sh, ScriptHandler.AFTER_LAYOUT, cmRunTime); // COMPUTE THE PLOT AREA Bounds boPlot = cmRunTime.getPlot().getBounds(); Insets insPlot = cmRunTime.getPlot().getInsets(); boPlot = boPlot.adjustedInstance(insPlot); ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_COMPUTATIONS, cmRunTime, oComputations); long lTimer = System.currentTimeMillis(); if (iChartType == WITH_AXES) { PlotWith2DAxes pwa = (PlotWith2DAxes) oComputations; try { pwa.compute(boPlot); } catch (Exception ex ) { ex.printStackTrace(); throw new GenerationException(ex); } } else if (iChartType == WITHOUT_AXES) { PlotWithoutAxes pwoa = (PlotWithoutAxes) oComputations; try { pwoa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } } ScriptHandler.callFunction(sh, ScriptHandler.AFTER_COMPUTATIONS, cmRunTime, oComputations); final Collection co = lhmRenderers.values(); final LegendItemRenderingHints[] lirha = (LegendItemRenderingHints[]) co.toArray(EMPTY_LIRHA); final int iSize = lhmRenderers.size(); BaseRenderer br; for (int i = 0; i < iSize; i++) { br = lirha[i].getRenderer(); br.set(brna); br.set(xs); try { if (br.getComputations() instanceof PlotWithoutAxes) { br.set(((PlotWithoutAxes) br.getComputations()).getSeriesRenderingHints(br.getSeries())); } else { br.set(((PlotWith2DAxes) br.getComputations()).getSeriesRenderingHints(br.getSeries())); } ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_COMPUTE_SERIES, br.getSeries()); br.compute(bo, cmRunTime.getPlot(), br.getSeriesRenderingHints()); ScriptHandler.callFunction(sh, ScriptHandler.AFTER_COMPUTE_SERIES, br.getSeries()); } catch (Exception ex ) { throw new GenerationException(ex); } } il.log(ILogger.INFORMATION, "Time to compute plot (without axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); final GeneratedChartState gcs = new GeneratedChartState(xs, cmRunTime, lhmRenderers, oComputations); if (sh != null) { sh.setGeneratedChartState(gcs); ScriptHandler.callFunction(sh, ScriptHandler.FINISH_GENERATION, gcs); } return gcs; } /** * This method may be used to minimize re-computation of the chart if ONLY the dataset content has changed. * Attribute changes require a new chart build. * * @param gcs * A previously built chart * * @throws GenerationException */ public final void refresh(GeneratedChartState gcs) throws GenerationException { Chart cm = gcs.getChartModel(); ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.BEFORE_COMPUTATIONS, gcs); // COMPUTE THE PLOT AREA long lTimer = System.currentTimeMillis(); int iChartType = gcs.getType(); Bounds boPlot = cm.getPlot().getBounds(); Insets insPlot = cm.getPlot().getInsets(); boPlot = boPlot.adjustedInstance(insPlot); final ILogger il = DefaultLoggerImpl.instance(); if (iChartType == WITH_AXES) { PlotWith2DAxes pwa = (PlotWith2DAxes) gcs.getComputations(); try { pwa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } il.log(ILogger.INFORMATION, "Time to compute plot (with axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); } else if (iChartType == WITHOUT_AXES) { PlotWithoutAxes pwoa = (PlotWithoutAxes) gcs.getComputations(); try { pwoa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } il.log(ILogger.INFORMATION, "Time to compute plot (without axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); } ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.AFTER_COMPUTATIONS, gcs); } /** * This method renders the pre-computed chart via the device renderer * * @param idr * @param gcs * * @throws GenerationException */ public final void render(IDeviceRenderer idr, GeneratedChartState gcs) throws RenderingException { final Chart cm = gcs.getChartModel(); ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.START_RENDERING, gcs); Legend lg = cm.getLegend(); lg.updateLayout(cm); // RE-ORGANIZE BLOCKS IF REQUIRED if (lg.getPosition() == Position.INSIDE_LITERAL) { int iType = gcs.getType(); if (iType == WITH_AXES) { Bounds bo = ((PlotWith2DAxes) gcs.getComputations()).getPlotBounds(); try { updateLegendInside(bo, lg, idr.getDisplayServer(), cm); } catch (GenerationException gex ) { throw new RenderingException(gex); } } } final LinkedHashMap lhm = (LinkedHashMap) gcs.getRenderers(); final int iSize = lhm.size(); BaseRenderer br; final Collection co = lhm.values(); final LegendItemRenderingHints[] lirha = (LegendItemRenderingHints[]) co.toArray(EMPTY_LIRHA); final DeferredCache dc = new DeferredCache(idr, cm); // USED IN RENDERING ELEMENTS WITH THE CORRECT Z-ORDER // USE SAME BOUNDS FOR RENDERING AS THOSE USED TO PREVIOUSLY COMPUTE THE CHART OFFSCREEN final Bounds bo = gcs.getChartModel().getBlock().getBounds(); idr.setProperty(IDeviceRenderer.EXPECTED_BOUNDS, bo .scaledInstance(idr.getDisplayServer().getDpiResolution() / 72d)); idr.before(); // INITIALIZATION BEFORE RENDERING BEGINS for (int i = 0; i < iSize; i++) { br = lirha[i].getRenderer(); br.set(dc); br.set(idr); try { br.render(lhm, bo); // 'bo' MUST BE CLIENT AREA WITHIN ANY // 'shell' OR 'frame' } catch (Exception ex ) { ex.printStackTrace(); throw new RenderingException(ex); } } idr.after(); // ANY CLEANUP AFTER THE CHART HAS BEEN RENDERED ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.FINISH_RENDERING, gcs); } /** * * @param boContainer * @param lg * @param ids * @param cm * @throws GenerationException */ private static final void updateLegendInside(Bounds boContainer, Legend lg, IDisplayServer ids, Chart cm) throws GenerationException { final double dScale = ids.getDpiResolution() / 72d; double dX, dY; final Size sz = lg.getPreferredSize(ids, cm); boContainer = boContainer.scaledInstance(1d / dScale); // USE ANCHOR IN POSITIONING THE LEGEND CLIENT AREA WITHIN THE BLOCK // SLACK SPACE if (lg.isSetAnchor()) { final int iAnchor = lg.getAnchor().getValue(); switch (iAnchor) { case Anchor.NORTH: case Anchor.NORTH_EAST: case Anchor.NORTH_WEST: dY = boContainer.getTop(); break; case Anchor.SOUTH: case Anchor.SOUTH_EAST: case Anchor.SOUTH_WEST: dY = boContainer.getTop() + boContainer.getHeight() - sz.getHeight(); break; default: // CENTERED dY = boContainer.getTop() + (boContainer.getHeight() - sz.getHeight()) / 2; break; } switch (iAnchor) { case Anchor.WEST: case Anchor.SOUTH_WEST: case Anchor.NORTH_WEST: dX = boContainer.getLeft(); break; case Anchor.NORTH_EAST: case Anchor.EAST: case Anchor.SOUTH_EAST: dX = boContainer.getLeft() + boContainer.getWidth() - sz.getWidth(); break; default: // CENTERED dX = boContainer.getLeft() + (boContainer.getWidth() - sz.getWidth()) / 2; break; } } else { dX = boContainer.getLeft() + (boContainer.getWidth() - sz.getWidth()) / 2; dY = boContainer.getTop() + (boContainer.getHeight() - sz.getHeight()) / 2; } lg.getBounds().set(dX, dY, sz.getWidth(), sz.getHeight()); } }
chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/factory/Generator.java
/*********************************************************************** * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.factory; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Locale; import org.eclipse.birt.chart.computation.IConstants; import org.eclipse.birt.chart.computation.withaxes.LegendItemRenderingHints; import org.eclipse.birt.chart.computation.withaxes.PlotWith2DAxes; import org.eclipse.birt.chart.computation.withoutaxes.PlotWithoutAxes; import org.eclipse.birt.chart.device.IDeviceRenderer; import org.eclipse.birt.chart.device.IDisplayServer; import org.eclipse.birt.chart.exception.GenerationException; import org.eclipse.birt.chart.exception.OverlapException; import org.eclipse.birt.chart.exception.RenderingException; import org.eclipse.birt.chart.exception.ScriptException; import org.eclipse.birt.chart.exception.UnsupportedFeatureException; import org.eclipse.birt.chart.log.DefaultLoggerImpl; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.ScriptHandler; import org.eclipse.birt.chart.model.attribute.Anchor; import org.eclipse.birt.chart.model.attribute.Bounds; import org.eclipse.birt.chart.model.attribute.ChartDimension; import org.eclipse.birt.chart.model.attribute.Insets; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.birt.chart.model.attribute.Size; import org.eclipse.birt.chart.model.attribute.impl.BoundsImpl; import org.eclipse.birt.chart.model.layout.Block; import org.eclipse.birt.chart.model.layout.LayoutManager; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.render.BaseRenderer; import org.eclipse.emf.ecore.util.EcoreUtil; import org.mozilla.javascript.Scriptable; /** * This class provides a factory entry point into building a chart for a given model. It is implemented as a singleton * and does not maintain any state information hence allowing multi-threaded requests for a single Generator instance. * * @author Actuate Corporation */ public final class Generator { /** * */ private static final int UNDEFINED = IConstants.UNDEFINED; /** * */ static final int WITH_AXES = 1; /** * */ static final int WITHOUT_AXES = 2; /** * */ private static final LegendItemRenderingHints[] EMPTY_LIRHA = new LegendItemRenderingHints[0]; /** * The internal singleton Generator reference */ private static Generator g = null; /** * A private constructor */ private Generator() { } /** * * @return A singleton instance for the Generator. */ public static synchronized final Generator instance() { if (g == null) { g = new Generator(); } return g; } /** * This method builds the chart (offscreen) using the provided display server * * @param xs * @param cmDesignTime * @param scParent * @param bo * @param lo * @return * @throws GenerationException */ public final GeneratedChartState build(IDisplayServer xs, Chart cmDesignTime, Scriptable scParent, Bounds bo, Locale lo) throws GenerationException { if (xs == null || cmDesignTime == null || bo == null) { throw new GenerationException("Illegal 'null' value passed as an argument to build a chart"); } if (cmDesignTime.getDimension() == ChartDimension.THREE_DIMENSIONAL_LITERAL) { throw new GenerationException(new UnsupportedFeatureException("3D charts are not yet supported")); } Chart cmRunTime = (Chart) EcoreUtil.copy(cmDesignTime); if (lo == null) { lo = Locale.getDefault(); } final String sScriptContent = cmRunTime.getScript(); ScriptHandler sh = null; if (sScriptContent != null) { sh = new ScriptHandler(); try { sh.init(scParent); sh.setRunTimeModel(cmRunTime); cmRunTime.setScriptHandler(sh); sh.register(sScriptContent); ScriptHandler.callFunction(sh, ScriptHandler.START_GENERATION, cmRunTime); } catch (ScriptException sx ) { throw new GenerationException(sx); } } // SETUP THE COMPUTATIONS int iChartType = UNDEFINED; Object oComputations = null; if (cmRunTime instanceof ChartWithAxes) { iChartType = WITH_AXES; oComputations = new PlotWith2DAxes(xs, (ChartWithAxes) cmRunTime, lo); } else if (cmRunTime instanceof ChartWithoutAxes) { iChartType = WITHOUT_AXES; oComputations = new PlotWithoutAxes(xs, (ChartWithoutAxes) cmRunTime, lo); } if (oComputations == null) { throw new GenerationException("Unable to compute chart defined by model [" + cmRunTime + "]"); } // OBTAIN THE RENDERERS final ILogger il = DefaultLoggerImpl.instance(); final LinkedHashMap lhmRenderers = new LinkedHashMap(); BaseRenderer[] brna = null; try { brna = BaseRenderer.instances(cmRunTime, oComputations); for (int i = 0; i < brna.length; i++) { lhmRenderers.put(brna[i].getSeries(), new LegendItemRenderingHints(brna[i], BoundsImpl.create(0, 0, 0, 0))); } } catch (Exception ex ) { ex.printStackTrace(); throw new GenerationException(ex); } // PERFORM THE BLOCKS' LAYOUT Block bl = cmRunTime.getBlock(); final LayoutManager lm = new LayoutManager(bl); ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_LAYOUT, cmRunTime); try { lm.doLayout_tmp(xs, cmRunTime, bo); } catch (OverlapException oex ) { throw new GenerationException(oex); } ScriptHandler.callFunction(sh, ScriptHandler.AFTER_LAYOUT, cmRunTime); // COMPUTE THE PLOT AREA Bounds boPlot = cmRunTime.getPlot().getBounds(); Insets insPlot = cmRunTime.getPlot().getInsets(); boPlot = boPlot.adjustedInstance(insPlot); ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_COMPUTATIONS, cmRunTime, oComputations); long lTimer = System.currentTimeMillis(); if (iChartType == WITH_AXES) { PlotWith2DAxes pwa = (PlotWith2DAxes) oComputations; try { pwa.compute(boPlot); } catch (Exception ex ) { ex.printStackTrace(); throw new GenerationException(ex); } } else if (iChartType == WITHOUT_AXES) { PlotWithoutAxes pwoa = (PlotWithoutAxes) oComputations; try { pwoa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } } ScriptHandler.callFunction(sh, ScriptHandler.AFTER_COMPUTATIONS, cmRunTime, oComputations); final Collection co = lhmRenderers.values(); final LegendItemRenderingHints[] lirha = (LegendItemRenderingHints[]) co.toArray(EMPTY_LIRHA); final int iSize = lhmRenderers.size(); BaseRenderer br; for (int i = 0; i < iSize; i++) { br = lirha[i].getRenderer(); br.set(brna); br.set(xs); try { if (br.getComputations() instanceof PlotWithoutAxes) { br.set(((PlotWithoutAxes) br.getComputations()).getSeriesRenderingHints(br.getSeries())); } else { br.set(((PlotWith2DAxes) br.getComputations()).getSeriesRenderingHints(br.getSeries())); } ScriptHandler.callFunction(sh, ScriptHandler.BEFORE_COMPUTE_SERIES, br.getSeries()); br.compute(bo, cmRunTime.getPlot(), br.getSeriesRenderingHints()); ScriptHandler.callFunction(sh, ScriptHandler.AFTER_COMPUTE_SERIES, br.getSeries()); } catch (Exception ex ) { throw new GenerationException(ex); } } il.log(ILogger.INFORMATION, "Time to compute plot (without axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); final GeneratedChartState gcs = new GeneratedChartState(xs, cmRunTime, lhmRenderers, oComputations); if (sh != null) { sh.setGeneratedChartState(gcs); ScriptHandler.callFunction(sh, ScriptHandler.FINISH_GENERATION, gcs); } return gcs; } /** * This method may be used to minimize re-computation of the chart if ONLY the dataset content has changed. * Attribute changes require a new chart build. * * @param gcs * A previously built chart * * @throws GenerationException */ public final void refresh(GeneratedChartState gcs) throws GenerationException { Chart cm = gcs.getChartModel(); ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.BEFORE_COMPUTATIONS, gcs); // COMPUTE THE PLOT AREA long lTimer = System.currentTimeMillis(); int iChartType = gcs.getType(); Bounds boPlot = cm.getPlot().getBounds(); Insets insPlot = cm.getPlot().getInsets(); boPlot = boPlot.adjustedInstance(insPlot); final ILogger il = DefaultLoggerImpl.instance(); if (iChartType == WITH_AXES) { PlotWith2DAxes pwa = (PlotWith2DAxes) gcs.getComputations(); try { pwa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } il.log(ILogger.INFORMATION, "Time to compute plot (with axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); } else if (iChartType == WITHOUT_AXES) { PlotWithoutAxes pwoa = (PlotWithoutAxes) gcs.getComputations(); try { pwoa.compute(boPlot); } catch (Exception ex ) { throw new GenerationException(ex); } il.log(ILogger.INFORMATION, "Time to compute plot (without axes) = " + (System.currentTimeMillis() - lTimer) + " ms"); } ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.AFTER_COMPUTATIONS, gcs); } /** * This method renders the pre-computed chart via the device renderer * * @param idr * @param gcs * * @throws GenerationException */ public final void render(IDeviceRenderer idr, GeneratedChartState gcs) throws RenderingException { final Chart cm = gcs.getChartModel(); ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.START_RENDERING, gcs); Legend lg = cm.getLegend(); lg.updateLayout(cm); // RE-ORGANIZE BLOCKS IF REQUIRED if (lg.getPosition() == Position.INSIDE_LITERAL) { int iType = gcs.getType(); if (iType == WITH_AXES) { Bounds bo = ((PlotWith2DAxes) gcs.getComputations()).getPlotBounds(); try { updateLegendInside(bo, lg, idr.getDisplayServer(), cm); } catch (GenerationException gex ) { throw new RenderingException(gex); } } } final LinkedHashMap lhm = (LinkedHashMap) gcs.getRenderers(); final int iSize = lhm.size(); BaseRenderer br; final Collection co = lhm.values(); final LegendItemRenderingHints[] lirha = (LegendItemRenderingHints[]) co.toArray(EMPTY_LIRHA); final DeferredCache dc = new DeferredCache(idr, cm); // USED IN RENDERING ELEMENTS WITH THE CORRECT Z-ORDER // USE SAME BOUNDS FOR RENDERING AS THOSE USED TO PREVIOUSLY COMPUTE THE CHART OFFSCREEN final Bounds bo = gcs.getChartModel().getBlock().getBounds(); idr.setProperty(IDeviceRenderer.EXPECTED_BOUNDS, bo .scaledInstance(idr.getDisplayServer().getDpiResolution() / 72d)); idr.before(); // INITIALIZATION BEFORE RENDERING BEGINS for (int i = 0; i < iSize; i++) { br = lirha[i].getRenderer(); br.set(dc); br.set(idr); try { br.render(lhm, bo); // 'bo' MUST BE CLIENT AREA WITHIN ANY // 'shell' OR 'frame' } catch (Exception ex ) { ex.printStackTrace(); throw new RenderingException(ex); } } idr.after(); // ANY CLEANUP AFTER THE CHART HAS BEEN RENDERED ScriptHandler.callFunction(cm.getScriptHandler(), ScriptHandler.FINISH_RENDERING, gcs); } /** * * @param boContainer * @param lg * @param ids * @param cm * @throws GenerationException */ private static final void updateLegendInside(Bounds boContainer, Legend lg, IDisplayServer ids, Chart cm) throws GenerationException { final double dScale = ids.getDpiResolution() / 72d; double dX, dY; final Size sz = lg.getPreferredSize(ids, cm); boContainer = boContainer.scaledInstance(1d / dScale); // USE ANCHOR IN POSITIONING THE LEGEND CLIENT AREA WITHIN THE BLOCK // SLACK SPACE if (lg.isSetAnchor()) { final int iAnchor = lg.getAnchor().getValue(); switch (iAnchor) { case Anchor.NORTH: case Anchor.NORTH_EAST: case Anchor.NORTH_WEST: dY = boContainer.getTop(); break; case Anchor.SOUTH: case Anchor.SOUTH_EAST: case Anchor.SOUTH_WEST: dY = boContainer.getTop() + boContainer.getHeight() - sz.getHeight(); break; default: // CENTERED dY = boContainer.getTop() + (boContainer.getHeight() - sz.getHeight()) / 2; break; } switch (iAnchor) { case Anchor.WEST: case Anchor.SOUTH_WEST: case Anchor.NORTH_WEST: dX = boContainer.getLeft(); break; case Anchor.NORTH_EAST: case Anchor.EAST: case Anchor.SOUTH_EAST: dX = boContainer.getLeft() + boContainer.getWidth() - sz.getWidth(); break; default: // CENTERED dX = boContainer.getLeft() + (boContainer.getWidth() - sz.getWidth()) / 2; break; } } else { dX = boContainer.getLeft() + (boContainer.getWidth() - sz.getWidth()) / 2; dY = boContainer.getTop() + (boContainer.getHeight() - sz.getHeight()) / 2; } lg.getBounds().set(dX, dY, sz.getWidth(), sz.getHeight()); } }
Updated generator to reuse the design-time model's script handler as the runtime model's script handler
chart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/factory/Generator.java
Updated generator to reuse the design-time model's script handler as the runtime model's script handler
<ide><path>hart/org.eclipse.birt.chart.engine/src/org/eclipse/birt/chart/factory/Generator.java <ide> } <ide> <ide> final String sScriptContent = cmRunTime.getScript(); <del> ScriptHandler sh = null; <del> if (sScriptContent != null) <add> ScriptHandler sh = cmDesignTime.getScriptHandler(); <add> if (sh == null && sScriptContent != null) // NOT PREVIOUSLY DEFINED BY REPORTITEM ADAPTER <ide> { <ide> sh = new ScriptHandler(); <ide> try <ide> sh.setRunTimeModel(cmRunTime); <ide> cmRunTime.setScriptHandler(sh); <ide> sh.register(sScriptContent); <del> ScriptHandler.callFunction(sh, ScriptHandler.START_GENERATION, cmRunTime); <ide> } <ide> catch (ScriptException sx ) <ide> { <ide> throw new GenerationException(sx); <ide> } <ide> } <add> else if (sh != null) // COPY SCRIPTS FROM DESIGNTIME TO RUNTIME INSTANCE <add> { <add> cmRunTime.setScriptHandler(sh); <add> } <ide> <ide> // SETUP THE COMPUTATIONS <add> ScriptHandler.callFunction(sh, ScriptHandler.START_GENERATION, cmRunTime); <ide> int iChartType = UNDEFINED; <ide> Object oComputations = null; <ide> if (cmRunTime instanceof ChartWithAxes)
Java
apache-2.0
error: pathspec 'strongbox-cron-tasks/src/main/java/org.carlspring.strongbox/cron/api/jobs/RebuildMetadataCronJob.java' did not match any file(s) known to git
1c1f6bebd871faa9647e3ff1859a313235891c53
1
sbespalov/strongbox,sbespalov/strongbox,nenko-tabakov/strongbox,sbespalov/strongbox,strongbox/strongbox,AlexOreshkevich/strongbox,strongbox/strongbox,sbespalov/strongbox,strongbox/strongbox,strongbox/strongbox
package org.carlspring.strongbox.cron.api.jobs; import org.carlspring.strongbox.services.ArtifactMetadataService; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.security.NoSuchAlgorithmException; /** * @author Kate Novik */ public class RebuildMetadataCronJob extends JavaCronJob { private final Logger logger = LoggerFactory.getLogger(RebuildMetadataCronJob.class); @Autowired ArtifactMetadataService artifactMetadataService; @Override protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { logger.debug("Executed RebuildMetadataCronJob."); try { String storageId = getConfiguration().getProperty("storageId"); String repositoryId = getConfiguration().getProperty("repositoryId"); String basePath = getConfiguration().getProperty("basePath"); artifactMetadataService.rebuildMetadata(storageId, repositoryId, basePath); } catch (IOException | XmlPullParserException | NoSuchAlgorithmException e) { e.printStackTrace(); logger.error("IOException: ", e); } } }
strongbox-cron-tasks/src/main/java/org.carlspring.strongbox/cron/api/jobs/RebuildMetadataCronJob.java
SB-564: Created class RebuildMetadataCronJob for executing method rebuild metadata of Maven artifacts on a schedule.
strongbox-cron-tasks/src/main/java/org.carlspring.strongbox/cron/api/jobs/RebuildMetadataCronJob.java
SB-564: Created class RebuildMetadataCronJob for executing method rebuild metadata of Maven artifacts on a schedule.
<ide><path>trongbox-cron-tasks/src/main/java/org.carlspring.strongbox/cron/api/jobs/RebuildMetadataCronJob.java <add>package org.carlspring.strongbox.cron.api.jobs; <add> <add>import org.carlspring.strongbox.services.ArtifactMetadataService; <add>import org.codehaus.plexus.util.xml.pull.XmlPullParserException; <add>import org.quartz.JobExecutionContext; <add>import org.quartz.JobExecutionException; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add>import org.springframework.beans.factory.annotation.Autowired; <add> <add>import java.io.IOException; <add>import java.security.NoSuchAlgorithmException; <add> <add>/** <add> * @author Kate Novik <add> */ <add>public class RebuildMetadataCronJob extends JavaCronJob { <add> <add> private final Logger logger = LoggerFactory.getLogger(RebuildMetadataCronJob.class); <add> <add> @Autowired <add> ArtifactMetadataService artifactMetadataService; <add> <add> @Override <add> protected void executeInternal(JobExecutionContext jobExecutionContext) <add> throws JobExecutionException <add> { <add> logger.debug("Executed RebuildMetadataCronJob."); <add> <add> try <add> { <add> String storageId = getConfiguration().getProperty("storageId"); <add> String repositoryId = getConfiguration().getProperty("repositoryId"); <add> String basePath = getConfiguration().getProperty("basePath"); <add> artifactMetadataService.rebuildMetadata(storageId, repositoryId, basePath); <add> } <add> catch (IOException | XmlPullParserException | NoSuchAlgorithmException e) <add> { <add> e.printStackTrace(); <add> logger.error("IOException: ", e); <add> } <add> <add> } <add>}
Java
apache-2.0
error: pathspec 'src/test/design/pattern/behavior/testMediator2.java' did not match any file(s) known to git
fa47ff65b5bc8ae965ff6940d28a80bbf3574c16
1
cheyiliu/test4java
package test.design.pattern.behavior; import java.util.ArrayList; import java.util.List; /** * http://blog.csdn.net/qbg19881206/article/details/18772201 */ /** * 中介者模式将一个网状的系统结构变成一个以中介者对象为中心的星形结构, * 在这个星型结构中,使用中介者对象与其他对象的一对多关系来取代原有对象之间的多对多关系。 * 中介者模式在事件驱动类软件中应用较为广泛,特别是基于GUI(Graphical User Interface, * 图形用户界面)的应用软件,此外,在类与类之间存在错综复杂的关联关系的系统中, 中介者模式都能得到较好的应用。 * * @author qbg */ public class testMediator2 { public static void main(String[] args) { List<Person2> ps = new ArrayList<Person2>(); Person2 b0 = new Boy(); ps.add(b0); Person2 b1 = new Boy(); ps.add(b1); Person2 g0 = new Girl(); ps.add(g0); Person2 g1 = new Girl(); ps.add(g1); Mediator2 mediator = new ConcreteMediator(ps); b0.setInterest("创业"); b0.setMediator(mediator); b1.setInterest("挣钱"); b1.setMediator(mediator); g0.setInterest("逛街"); g0.setMediator(mediator); g1.setInterest("持家"); g1.setMediator(mediator); b0.interest("持家"); System.out.println("==========男女有别==============="); g0.interest("挣钱"); } } /** * 中介者抽象接口 */ interface Mediator2 { public void interestChanged(Person2 p); } /** * 具体中介者,充当媒婆的角色。 */ class ConcreteMediator implements Mediator2 { private List<Person2> miai; // 相亲队伍 public ConcreteMediator(List<Person2> ps) { this.miai = ps; } /** * 相亲者兴趣改变时进行响应,重新匹配候选人. 封装同事对象之间的交互. */ @Override public void interestChanged(Person2 p) { boolean succeed = false; Person2 candidate = null; for (Person2 person : miai) { // 不是相亲者本身且兴趣相同则匹配成功! if (person != p && p.interest.equals(person.interest)) { succeed = true; candidate = person; break; } } p.update(succeed); if (candidate != null) { candidate.update(succeed); } } } /** * 人,抽象同事类 */ abstract class Person2 { protected Mediator2 mediator;// 中介者引用 protected String interest;// 兴趣 public void setMediator(Mediator2 m) { this.mediator = m; } public void setInterest(String in) { this.interest = in; } public void interest(String interest) { this.interest = interest; mediator.interestChanged(this); } public abstract void update(boolean succeed); } /** * 男生,具体同事类 */ class Boy extends Person2 { @Override public void update(boolean succeed) { if (succeed) { System.out.println("相亲成功,大喝一顿!!!"); } else { System.out.println("相亲失败,明天再战!!!"); } } } /** * 女生,具体同事类 */ class Girl extends Person2 { @Override public void update(boolean succeed) { if (succeed) { System.out.println("找到白马王子了,去KTV狂欢!"); } else { System.out.println("黑驴都没找到,全是骡子,呜呜...."); } } }
src/test/design/pattern/behavior/testMediator2.java
add Mediator中介者模式 2
src/test/design/pattern/behavior/testMediator2.java
add Mediator中介者模式 2
<ide><path>rc/test/design/pattern/behavior/testMediator2.java <add> <add>package test.design.pattern.behavior; <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>/** <add> * http://blog.csdn.net/qbg19881206/article/details/18772201 <add> */ <add>/** <add> * 中介者模式将一个网状的系统结构变成一个以中介者对象为中心的星形结构, <add> * 在这个星型结构中,使用中介者对象与其他对象的一对多关系来取代原有对象之间的多对多关系。 <add> * 中介者模式在事件驱动类软件中应用较为广泛,特别是基于GUI(Graphical User Interface, <add> * 图形用户界面)的应用软件,此外,在类与类之间存在错综复杂的关联关系的系统中, 中介者模式都能得到较好的应用。 <add> * <add> * @author qbg <add> */ <add>public class testMediator2 { <add> public static void main(String[] args) { <add> List<Person2> ps = new ArrayList<Person2>(); <add> Person2 b0 = new Boy(); <add> ps.add(b0); <add> Person2 b1 = new Boy(); <add> ps.add(b1); <add> Person2 g0 = new Girl(); <add> ps.add(g0); <add> Person2 g1 = new Girl(); <add> ps.add(g1); <add> Mediator2 mediator = new ConcreteMediator(ps); <add> b0.setInterest("创业"); <add> b0.setMediator(mediator); <add> b1.setInterest("挣钱"); <add> b1.setMediator(mediator); <add> g0.setInterest("逛街"); <add> g0.setMediator(mediator); <add> g1.setInterest("持家"); <add> g1.setMediator(mediator); <add> <add> b0.interest("持家"); <add> System.out.println("==========男女有别==============="); <add> g0.interest("挣钱"); <add> } <add>} <add> <add>/** <add> * 中介者抽象接口 <add> */ <add>interface Mediator2 { <add> public void interestChanged(Person2 p); <add>} <add> <add>/** <add> * 具体中介者,充当媒婆的角色。 <add> */ <add>class ConcreteMediator implements Mediator2 { <add> private List<Person2> miai; // 相亲队伍 <add> <add> public ConcreteMediator(List<Person2> ps) { <add> this.miai = ps; <add> } <add> <add> /** <add> * 相亲者兴趣改变时进行响应,重新匹配候选人. 封装同事对象之间的交互. <add> */ <add> @Override <add> public void interestChanged(Person2 p) { <add> boolean succeed = false; <add> Person2 candidate = null; <add> for (Person2 person : miai) { <add> // 不是相亲者本身且兴趣相同则匹配成功! <add> if (person != p && p.interest.equals(person.interest)) { <add> succeed = true; <add> candidate = person; <add> break; <add> } <add> } <add> p.update(succeed); <add> if (candidate != null) { <add> candidate.update(succeed); <add> } <add> } <add> <add>} <add> <add>/** <add> * 人,抽象同事类 <add> */ <add>abstract class Person2 { <add> protected Mediator2 mediator;// 中介者引用 <add> protected String interest;// 兴趣 <add> <add> public void setMediator(Mediator2 m) { <add> this.mediator = m; <add> } <add> <add> public void setInterest(String in) { <add> this.interest = in; <add> } <add> <add> public void interest(String interest) { <add> this.interest = interest; <add> mediator.interestChanged(this); <add> } <add> <add> public abstract void update(boolean succeed); <add>} <add> <add>/** <add> * 男生,具体同事类 <add> */ <add>class Boy extends Person2 { <add> <add> @Override <add> public void update(boolean succeed) { <add> if (succeed) { <add> System.out.println("相亲成功,大喝一顿!!!"); <add> } else { <add> System.out.println("相亲失败,明天再战!!!"); <add> } <add> } <add>} <add> <add>/** <add> * 女生,具体同事类 <add> */ <add>class Girl extends Person2 { <add> <add> @Override <add> public void update(boolean succeed) { <add> if (succeed) { <add> System.out.println("找到白马王子了,去KTV狂欢!"); <add> } else { <add> System.out.println("黑驴都没找到,全是骡子,呜呜...."); <add> } <add> } <add>}
Java
lgpl-2.1
5c305136a6ce0a004e916e3f3e3752eea7886f16
0
pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
/* * Copyright 2005-2007, XpertNet SARL, and individual contributors as indicated * by the contributors.txt. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.plugin.scheduler; import groovy.lang.Binding; import groovy.lang.GroovyShell; import org.codehaus.groovy.control.CompilationFailedException; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.api.Context; /** * The task that will get executed by the Scheduler when the Job is triggered. This task in * turn calls a Groovy script to perform the execution. * * <p><b>Important:</b>: Note that the script will execute in the XWiki Context that was set at * the time the Job was scheduled for execution. For example calling <code>context.getDoc()</code> * will return the current document that was set at that time and not the current document that is * set when the Groovy script executes... * * @version $Id: $ */ public class GroovyTask implements Job { /** * Executes the Groovy script passed in the <code>script</code> property of the * {@link com.xpn.xwiki.plugin.scheduler.SchedulerPlugin#TASK_CLASS} object extracted from the * XWiki context passed in the Quartz's Job execution context. The XWiki Task object is * looked for in the current document that was set in the context at the time the Job was * scheduled. * * @param context the Quartz execution context containing the XWiki context from which the * script to execute is retrieved * @exception JobExecutionException if the script fails to execute or if the user didn't have * programming rights when the Job was scheduled * @see Job#execute(org.quartz.JobExecutionContext) */ public void execute(JobExecutionContext context) throws JobExecutionException { try { JobDataMap data = context.getJobDetail().getJobDataMap(); // The XWiki context was saved in the Job execution data map. Get it as we'll retrieve // the script to execute from it. Context xcontext = (Context) data.get("context"); Api api = new Api(xcontext.getContext()); if (api.hasProgrammingRights()) { // The current task id. This is needed to find the correct XWiki Task object that // was stored in the current document as there can be several tasks stored in that // document. int task = data.getInt("task"); // Get the correct task object from the current doc set when the Job was // scheduled. BaseObject object = xcontext.getDoc().getObject(SchedulerPlugin.TASK_CLASS, task); Binding binding = new Binding(data.getWrappedMap()); GroovyShell shell = new GroovyShell(binding); // Execute the Groovy script shell.evaluate(object.getLargeStringValue("script")); } else { throw new JobExecutionException("The user [" + xcontext.getUser() + "] didn't have " + "programming rights when the job [" + context.getJobDetail().getName() + "] was scheduled."); } } catch (CompilationFailedException e) { throw new JobExecutionException("Failed to execute script for job [" + context.getJobDetail().getName() + "]", e, true); } } }
src/main/java/com/xpn/xwiki/plugin/scheduler/GroovyTask.java
/* * Copyright 2005-2007, XpertNet SARL, and individual contributors as indicated * by the contributors.txt. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.plugin.scheduler; import groovy.lang.Binding; import groovy.lang.GroovyShell; import org.codehaus.groovy.control.CompilationFailedException; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.api.Api; import com.xpn.xwiki.api.Context; public class GroovyTask implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { try { JobDataMap data = context.getJobDetail().getJobDataMap(); Context xcontext = (Context) data.get("context"); int task = data.getInt("task"); Binding binding = new Binding(data.getWrappedMap()); GroovyShell shell = new GroovyShell(binding); BaseObject object = xcontext.getDoc().getObject(SchedulerPlugin.TASK_CLASS, task); Api api = new Api(xcontext.getContext()); if (api.hasProgrammingRights()) { shell.evaluate(object.getLargeStringValue("script")); } } catch (CompilationFailedException e) { throw new JobExecutionException(e); } } }
XWIKI-807: Implement a Scheduler plugin * Fixed GroovyTask documentation * Moved programming check earlier so that unnecessary objects are not created * Handled case when the user ddidn't have programming rights when the job was scheduled * Added useful information to excpetions that were missing information (This is key and so many people don't handle exceptions correctly...) NOTE: No tests yet. git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@3970 f329d543-caf0-0310-9063-dda96c69346f
src/main/java/com/xpn/xwiki/plugin/scheduler/GroovyTask.java
XWIKI-807: Implement a Scheduler plugin
<ide><path>rc/main/java/com/xpn/xwiki/plugin/scheduler/GroovyTask.java <ide> import com.xpn.xwiki.api.Api; <ide> import com.xpn.xwiki.api.Context; <ide> <add>/** <add> * The task that will get executed by the Scheduler when the Job is triggered. This task in <add> * turn calls a Groovy script to perform the execution. <add> * <add> * <p><b>Important:</b>: Note that the script will execute in the XWiki Context that was set at <add> * the time the Job was scheduled for execution. For example calling <code>context.getDoc()</code> <add> * will return the current document that was set at that time and not the current document that is <add> * set when the Groovy script executes... <add> * <add> * @version $Id: $ <add> */ <ide> public class GroovyTask implements Job <ide> { <add> /** <add> * Executes the Groovy script passed in the <code>script</code> property of the <add> * {@link com.xpn.xwiki.plugin.scheduler.SchedulerPlugin#TASK_CLASS} object extracted from the <add> * XWiki context passed in the Quartz's Job execution context. The XWiki Task object is <add> * looked for in the current document that was set in the context at the time the Job was <add> * scheduled. <add> * <add> * @param context the Quartz execution context containing the XWiki context from which the <add> * script to execute is retrieved <add> * @exception JobExecutionException if the script fails to execute or if the user didn't have <add> * programming rights when the Job was scheduled <add> * @see Job#execute(org.quartz.JobExecutionContext) <add> */ <ide> public void execute(JobExecutionContext context) throws JobExecutionException <ide> { <ide> try { <ide> JobDataMap data = context.getJobDetail().getJobDataMap(); <add> <add> // The XWiki context was saved in the Job execution data map. Get it as we'll retrieve <add> // the script to execute from it. <ide> Context xcontext = (Context) data.get("context"); <del> int task = data.getInt("task"); <ide> <del> Binding binding = new Binding(data.getWrappedMap()); <del> GroovyShell shell = new GroovyShell(binding); <del> BaseObject object = xcontext.getDoc().getObject(SchedulerPlugin.TASK_CLASS, task); <ide> Api api = new Api(xcontext.getContext()); <add> <ide> if (api.hasProgrammingRights()) { <add> <add> // The current task id. This is needed to find the correct XWiki Task object that <add> // was stored in the current document as there can be several tasks stored in that <add> // document. <add> int task = data.getInt("task"); <add> <add> // Get the correct task object from the current doc set when the Job was <add> // scheduled. <add> BaseObject object = xcontext.getDoc().getObject(SchedulerPlugin.TASK_CLASS, task); <add> <add> Binding binding = new Binding(data.getWrappedMap()); <add> GroovyShell shell = new GroovyShell(binding); <add> <add> // Execute the Groovy script <ide> shell.evaluate(object.getLargeStringValue("script")); <add> <add> } else { <add> throw new JobExecutionException("The user [" + xcontext.getUser() + "] didn't have " <add> + "programming rights when the job [" + context.getJobDetail().getName() <add> + "] was scheduled."); <ide> } <ide> } catch (CompilationFailedException e) { <del> throw new JobExecutionException(e); <add> throw new JobExecutionException("Failed to execute script for job [" <add> + context.getJobDetail().getName() + "]", e, true); <ide> } <ide> } <ide> }
JavaScript
mit
3d3a1620677372152808e9e3bc478f203171e8de
0
scottbedard/oc-vuetober-theme,scottbedard/oc-vuetober-theme
var path = require('path'); var WriteFilePlugin = require('write-file-webpack-plugin'); // helper function to get the base url for theme assets // if no explicit value is set, we'll try to use the theme directory function getProductionBaseUrl(api, pluginOptions) { var baseUrl = pluginOptions.baseUrl; if (typeof baseUrl !== 'undefined') { return baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'; } return '/' + api.resolve('assets').split('/').slice(-3).join('/') + '/'; } // helper function for resolving configuration // returns undefined if object does not have property function resolveProperty(obj, p) { return p.split('.').reduce(function(p, k) { return p && p[k]; }, obj); } module.exports = (api, options) => { var isProduction = process.env.NODE_ENV === 'production'; var pluginOptions = resolveProperty(options, 'pluginOptions.vuetober') || { baseUrl: undefined, }; // use dev assets when not in production options.baseUrl = isProduction ? getProductionBaseUrl(api, pluginOptions) : 'http://localhost:8080/'; // set webpack's output directory to /assets options.outputDir = 'assets'; // save our only page to /pages api.chainWebpack(function(config) { config.plugin('html').tap(function(args) { Object.assign(args[0], { minify: Object.assign((args[0].minify || {}), { // comments will always need to be removed to preserve october's // theme configuration and php section at the top of the file. removeComments: true, }), filename: '../pages/index.htm', template: 'src/index.htm', }); return args; }); }); // // non-production // if (!isProduction) { api.configureWebpack(function(config) { return { devServer: { headers: { 'Access-Control-Allow-Origin': '*', }, }, plugins: [ new WriteFilePlugin({ test: /\.htm$/ }), ], }; }); } }
index.js
var path = require('path'); var WriteFilePlugin = require('write-file-webpack-plugin'); // helper function to get the base url for theme assets // if no explicit value is set, we'll try to use the theme directory function getProductionBaseUrl(api, pluginOptions) { var baseUrl = pluginOptions.baseUrl; if (typeof baseUrl !== 'undefined') { return baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'; } return api.resolve('assets').split('/').slice(-3).join('/') + '/'; } // helper function for resolving configuration // returns undefined if object does not have property function resolveProperty(obj, p) { return p.split('.').reduce(function(p, k) { return p && p[k]; }, obj); } module.exports = (api, options) => { var isProduction = process.env.NODE_ENV === 'production'; var pluginOptions = resolveProperty(options, 'pluginOptions.vuetober') || { baseUrl: undefined, }; // use dev assets when not in production options.baseUrl = isProduction ? getProductionBaseUrl(api, pluginOptions) : 'http://localhost:8080/'; // set webpack's output directory to /assets options.outputDir = 'assets'; // save our only page to /pages api.chainWebpack(function(config) { config.plugin('html').tap(function(args) { Object.assign(args[0], { minify: Object.assign((args[0].minify || {}), { // comments will always need to be removed to preserve october's // theme configuration and php section at the top of the file. removeComments: true, }), filename: '../pages/index.htm', template: 'src/index.htm', }); return args; }); }); // // non-production // if (!isProduction) { api.configureWebpack(function(config) { return { devServer: { headers: { 'Access-Control-Allow-Origin': '*', }, }, plugins: [ new WriteFilePlugin({ test: /\.htm$/ }), ], }; }); } }
fix production base url when no explicit config is present
index.js
fix production base url when no explicit config is present
<ide><path>ndex.js <ide> return baseUrl.endsWith('/') ? baseUrl : baseUrl + '/'; <ide> } <ide> <del> return api.resolve('assets').split('/').slice(-3).join('/') + '/'; <add> return '/' + api.resolve('assets').split('/').slice(-3).join('/') + '/'; <ide> } <ide> <ide> // helper function for resolving configuration
Java
mit
b5be741927518c2307a76ef2c8b0606827f2a7cf
0
ravis411/SimCity201
package residence.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import residence.HomeRole; import residence.HomeRole.AgentEvent; import residence.HomeRole.AgentState; import residence.gui.HomeRoleGui; import residence.test.mock.MockApartmentManager; import residence.test.mock.MockHome; import trace.AlertLog; import Person.PersonAgent; import Person.test.mock.MockRole; public class ResidenceTest1 extends TestCase { private PersonAgent myPerson; private MockApartmentManager manager; private MockHome home; private HomeRole homeRole; private HomeRoleGui gui; public static Test suite() { return new TestSuite(ResidenceTest1.class); } public void setUp() throws Exception{ super.setUp(); manager=new MockApartmentManager("Mock Manager"); home= new MockHome("Mock Home"); myPerson= new PersonAgent("PersonAgent",null); homeRole= new HomeRole(myPerson); homeRole.setLandlord(manager); manager.homeRole=homeRole; } //-------------------ELEMENTARY PRECONDITIONS-----------------// public void testHomeRolePreConditions(){ try { setUp(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("TEST FOR PRECONDITIONS"); assertTrue("Initial State shoud be doingNothing",homeRole.state==AgentState.DoingNothing); assertTrue("Size of inventory should be 2",homeRole.getInventory().size()==2); assertTrue("Size of features list should be 1",homeRole.getHomeFeatures().size()==1); assertTrue("First item of inventory should be Cooking Ingredient and it should have 2 of those",homeRole.getInventory().get(0).name.equals("Cooking Ingredient")); assertTrue("First item of inventory should be Cooking Ingredient and it should have 2 of those",homeRole.getInventory().get(0).quantity==2); assertTrue("First item of inventory should be Cleaning supply and it should have 2 of those",homeRole.getInventory().get(1).name.equals("Cleaning supply")); assertTrue("First item of inventory should be Cleaning supply and it should have 2 of those",homeRole.getInventory().get(1).quantity==2); assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).name.equals("Sink")); assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).working==true); } //-------------------MESSAGE CHECKING--------------------------// public void testHomeRoleMessages(){ try { setUp(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("TEST FOR MESSAGES AND STATECHANGE OPERATIONS"); assertTrue("The initial event state should be none",homeRole.event==AgentEvent.none); homeRole.msgEnterBuilding(); assertTrue("Now the event should be none",homeRole.event==AgentEvent.none); assertTrue("Now the state should be Cooking",homeRole.enterHome==true); homeRole.enterHome=false; homeRole.msgRentDue(100); assertTrue("Amount of rentOwed should be 100",homeRole.getRentOwed()==100); homeRole.pickAndExecuteAction(); assertTrue("Amount of rentOwed now should be 0",homeRole.getRentOwed()==0); homeRole.msgTired(); assertTrue("Now the state should be Sleeping",homeRole.state==AgentState.Sleeping); homeRole.msgMakeFood(); assertTrue("Now the state should be Cooking",homeRole.state==AgentState.Cooking); homeRole.msgRestockItem ("Cleaning supply", 2); homeRole.msgRestockItem("Cooking Ingredient",2); assertTrue("Size of inventory should still be 2",homeRole.getInventory().size()==2); assertTrue("First item of inventory should be Cooking Ingredient and it should have 4 of those",homeRole.getInventory().get(0).name.equals("Cooking Ingredient")); assertTrue("First item of inventory should be Cooking Ingredient and it should have 4 of those",homeRole.getInventory().get(0).quantity==4); assertTrue("First item of inventory should be Cleaning supply and it should have 4 of those",homeRole.getInventory().get(1).name.equals("Cleaning supply")); assertTrue("First item of inventory should be Cleaning supply and it should have 4 of those",homeRole.getInventory().get(1).quantity==4); //Setting the sink functionality to false then going to test maintenance homeRole.getHomeFeatures().get(0).working=false ;//doesnt work now manager.msgBrokenFeature(homeRole.getHomeFeatures().get(0).name, home); assertTrue("First item of feature list should be sink and it should be working after repair",homeRole.getHomeFeatures().get(0).working==true); homeRole.msgLeaveBuilding(); assertTrue("Now the event should be none",homeRole.event==AgentEvent.leaving); assertTrue("Now the leaveBuilding boolean should be true",homeRole.leaveHome==true); assertTrue("Now the enterHome boolean should be false",homeRole.enterHome==false); } }
src/residence/test/ResidenceTest1.java
package residence.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import residence.HomeRole; import residence.HomeRole.AgentEvent; import residence.HomeRole.AgentState; import residence.gui.HomeRoleGui; import residence.test.mock.MockApartmentManager; import residence.test.mock.MockHome; import trace.AlertLog; import Person.PersonAgent; import Person.test.mock.MockRole; public class ResidenceTest1 extends TestCase { private PersonAgent myPerson; private MockApartmentManager manager; private MockHome home; private HomeRole homeRole; private HomeRoleGui gui; public static Test suite() { return new TestSuite(ResidenceTest1.class); } public void setUp() throws Exception{ super.setUp(); manager=new MockApartmentManager("Mock Manager"); home= new MockHome("Mock Home"); myPerson= new PersonAgent("PersonAgent",null); homeRole= new HomeRole(myPerson); homeRole.setLandlord(manager); manager.homeRole=homeRole; } public void testHomeRole(){ try { setUp(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //-------------------ELEMENTARY PRECONDITIONS-----------------// assertTrue("Initial State shoud be doingNothing",homeRole.state==AgentState.DoingNothing); assertTrue("Size of inventory should be 2",homeRole.getInventory().size()==2); assertTrue("Size of features list should be 1",homeRole.getHomeFeatures().size()==1); assertTrue("First item of inventory should be Cooking Ingredient and it should have 2 of those",homeRole.getInventory().get(0).name.equals("Cooking Ingredient")); assertTrue("First item of inventory should be Cooking Ingredient and it should have 2 of those",homeRole.getInventory().get(0).quantity==2); assertTrue("First item of inventory should be Cleaning supply and it should have 2 of those",homeRole.getInventory().get(1).name.equals("Cleaning supply")); assertTrue("First item of inventory should be Cleaning supply and it should have 2 of those",homeRole.getInventory().get(1).quantity==2); assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).name.equals("Sink")); assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).working==true); //-------------------MESSAGE CHECKING--------------------------// assertTrue("The initial event state should be none",homeRole.event==AgentEvent.none); homeRole.msgEnterBuilding(); assertTrue("Now the event should be none",homeRole.event==AgentEvent.none); assertTrue("Now the state should be Cooking",homeRole.enterHome==true); homeRole.enterHome=false; homeRole.msgRentDue(100); assertTrue("Amount of rentOwed should be 100",homeRole.getRentOwed()==100); homeRole.pickAndExecuteAction(); assertTrue("Amount of rentOwed now should be 0",homeRole.getRentOwed()==0); homeRole.msgTired(); assertTrue("Now the state should be Sleeping",homeRole.state==AgentState.Sleeping); System.err.println("fuck this shit"); homeRole.msgMakeFood(); assertTrue("Now the state should be Cooking",homeRole.state==AgentState.Cooking); homeRole.msgRestockItem ("Cleaning supply", 2); homeRole.msgRestockItem("Cooking Ingredient",2); assertTrue("Size of inventory should still be 2",homeRole.getInventory().size()==2); assertTrue("First item of inventory should be Cooking Ingredient and it should have 4 of those",homeRole.getInventory().get(0).name.equals("Cooking Ingredient")); assertTrue("First item of inventory should be Cooking Ingredient and it should have 4 of those",homeRole.getInventory().get(0).quantity==4); assertTrue("First item of inventory should be Cleaning supply and it should have 4 of those",homeRole.getInventory().get(1).name.equals("Cleaning supply")); assertTrue("First item of inventory should be Cleaning supply and it should have 4 of those",homeRole.getInventory().get(1).quantity==4); //Setting the sink functionality to false then going to test maintenance homeRole.getHomeFeatures().get(0).working=false ;//doesnt work now manager.msgBrokenFeature(homeRole.getHomeFeatures().get(0).name, home); assertTrue("First item of feature list should be sink and it should be working after repair",homeRole.getHomeFeatures().get(0).working==true); homeRole.msgLeaveBuilding(); assertTrue("Now the event should be none",homeRole.event==AgentEvent.leaving); assertTrue("Now the leaveBuilding boolean should be true",homeRole.leaveHome==true); assertTrue("Now the enterHome boolean should be false",homeRole.enterHome==false); } }
Removed profanity
src/residence/test/ResidenceTest1.java
Removed profanity
<ide><path>rc/residence/test/ResidenceTest1.java <ide> manager.homeRole=homeRole; <ide> <ide> } <del> public void testHomeRole(){ <add> //-------------------ELEMENTARY PRECONDITIONS-----------------// <add> public void testHomeRolePreConditions(){ <ide> try { <ide> setUp(); <ide> } catch (Exception e) { <ide> // TODO Auto-generated catch block <ide> e.printStackTrace(); <ide> } <add> System.out.println("TEST FOR PRECONDITIONS"); <ide> <del> //-------------------ELEMENTARY PRECONDITIONS-----------------// <ide> <ide> assertTrue("Initial State shoud be doingNothing",homeRole.state==AgentState.DoingNothing); <ide> assertTrue("Size of inventory should be 2",homeRole.getInventory().size()==2); <ide> assertTrue("First item of inventory should be Cleaning supply and it should have 2 of those",homeRole.getInventory().get(1).quantity==2); <ide> assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).name.equals("Sink")); <ide> assertTrue("First item of feature list should be sink and it should be working",homeRole.getHomeFeatures().get(0).working==true); <del> //-------------------MESSAGE CHECKING--------------------------// <add> <add> <add> <add> <add> } <add> //-------------------MESSAGE CHECKING--------------------------// <add> public void testHomeRoleMessages(){ <add> try { <add> setUp(); <add> } catch (Exception e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <add> <add> System.out.println("TEST FOR MESSAGES AND STATECHANGE OPERATIONS"); <add> <ide> assertTrue("The initial event state should be none",homeRole.event==AgentEvent.none); <ide> homeRole.msgEnterBuilding(); <ide> assertTrue("Now the event should be none",homeRole.event==AgentEvent.none); <ide> assertTrue("Amount of rentOwed now should be 0",homeRole.getRentOwed()==0); <ide> homeRole.msgTired(); <ide> assertTrue("Now the state should be Sleeping",homeRole.state==AgentState.Sleeping); <del> System.err.println("fuck this shit"); <ide> homeRole.msgMakeFood(); <ide> assertTrue("Now the state should be Cooking",homeRole.state==AgentState.Cooking); <ide> homeRole.msgRestockItem ("Cleaning supply", 2);
Java
mit
c51aec93d5d7448aad1444ccc90802155fafa753
0
FallenRiteMonk/ludus
package com.fallenritemonk.ludus.game; import android.content.DialogInterface; import android.graphics.Color; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; import com.fallenritemonk.ludus.R; import com.fallenritemonk.ludus.db.DatabaseHelper; import java.util.ArrayList; import java.util.Collections; import java.util.Random; /** * Created by FallenRiteMonk on 9/19/15. */ class GameField extends BaseAdapter { private final GameActivity activity; private final FloatingActionButton addFieldsButton; private final TextView headerCombos; private final GameModeEnum gameMode; private final DatabaseHelper dbHelper; private ArrayList<NumberField> fieldArray; private ArrayList<CombinePos> possibilities = new ArrayList<>(); private int selectedField; private int hint; private int stateOrder; public GameField(final GameActivity activity, FloatingActionButton addFieldsButton, TextView headerCombos, GameModeEnum gameMode, Boolean resume) { this.activity = activity; this.addFieldsButton = addFieldsButton; this.headerCombos = headerCombos; this.gameMode = gameMode; dbHelper = DatabaseHelper.getInstance(activity); if (resume) { resumeGame(); } else { newGame(); } } public void newGame() { fieldArray = new ArrayList<>(); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(2)); fieldArray.add(new NumberField(3)); fieldArray.add(new NumberField(4)); fieldArray.add(new NumberField(5)); fieldArray.add(new NumberField(6)); fieldArray.add(new NumberField(7)); fieldArray.add(new NumberField(8)); fieldArray.add(new NumberField(9)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(2)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(3)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(4)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(5)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(6)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(7)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(8)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(9)); if (gameMode == GameModeEnum.RANDOM) { Collections.shuffle(fieldArray, new Random(System.nanoTime())); } notifyDataSetChanged(); selectedField = -1; hint = -1; stateOrder = -1; findPossibilities(); dbHelper.clearDB(); saveState(); } private void resumeGame() { fieldsFromString(dbHelper.getLastState()); selectedField = -1; hint = -1; stateOrder = dbHelper.getLastStateOrder(); headerCombos.setText(String.valueOf(stateOrder)); findPossibilities(); } private void findPossibilities() { hideHint(); possibilities = new ArrayList<>(); for (int i = 0; i < fieldArray.size() - 1; i++) { if (fieldArray.get(i).getState() == NumberField.STATE.USED) continue; for (int ii = i + 1; ii < fieldArray.size(); ii++) { if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue; if (canBeCombined(i, ii)) { possibilities.add(new CombinePos(i, ii)); } break; } for (int ii = i + 9; ii < fieldArray.size(); ii += 9) { if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue; if (canBeCombined(i, ii)) { possibilities.add(new CombinePos(i, ii)); } break; } } if (possibilities.size() == 0) { addFieldsButton.setVisibility(View.VISIBLE); } else { addFieldsButton.setVisibility(View.GONE); } } private void hideHint() { if (hint != -1) { CombinePos shownHint = possibilities.get(hint); if (shownHint.getId1() < fieldArray.size() && fieldArray.get(shownHint.getId1()).getState() == NumberField.STATE.HINT) { fieldArray.get(shownHint.getId1()).setState(NumberField.STATE.UNUSED); } if (shownHint.getId2() < fieldArray.size() && fieldArray.get(shownHint.getId2()).getState() == NumberField.STATE.HINT) { fieldArray.get(shownHint.getId2()).setState(NumberField.STATE.UNUSED); } hint = -1; } } private boolean canBeCombined(int id1, int id2) { return id1 != id2 && !(fieldArray.get(id1).getNumber() + fieldArray.get(id2).getNumber() != 10 && fieldArray.get(id1).getNumber() != fieldArray.get(id2).getNumber()); } public void hint(GridView gridView) { if (possibilities.size() == 0) return; if (hint >= 0) { fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.UNUSED); fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.UNUSED); } hint = ++hint % possibilities.size(); fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.HINT); fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.HINT); gridView.smoothScrollToPosition(possibilities.get(hint).getId1()); notifyDataSetChanged(); } public void undo() { if (dbHelper.undo()) { resumeGame(); } } public void clicked(int id) { if (fieldArray.get(id).getState() == NumberField.STATE.USED) return; if (selectedField == -1) { selectedField = id; fieldArray.get(id).setState(NumberField.STATE.SELECTED); notifyDataSetChanged(); } else if (id == selectedField) { fieldArray.get(id).setState(NumberField.STATE.UNUSED); selectedField = -1; notifyDataSetChanged(); } else { combine(id); } } private void combine(int id) { boolean combined = false; for (CombinePos pos : possibilities) { if (pos.equals(new CombinePos(id, selectedField))) { fieldArray.get(id).setState(NumberField.STATE.USED); fieldArray.get(selectedField).setState(NumberField.STATE.USED); if (reduceFields()) { won(); } else { saveState(); findPossibilities(); } selectedField = -1; combined = true; break; } } if (!combined) { fieldArray.get(selectedField).setState(NumberField.STATE.UNUSED); selectedField = -1; } notifyDataSetChanged(); } private boolean reduceFields() { ArrayList<NumberField> deleteList = new ArrayList<>(); int usedCound = 0; for (int i = 0; i < fieldArray.size(); i++) { if (fieldArray.get(i).getState() == NumberField.STATE.USED) { if (++usedCound == 9){ deleteNine(i, deleteList); usedCound = 0; } } else { usedCound = 0; } } fieldArray.removeAll(deleteList); if (usedCound == fieldArray.size()) { fieldArray.clear(); } return fieldArray.isEmpty(); } private void deleteNine(int index, ArrayList<NumberField> deleteList) { ArrayList<NumberField> tempList = new ArrayList<>(); for (int i = 0; i < 9; i++) { if (deleteList.contains(fieldArray.get(index - i))) { return; } else { tempList.add(fieldArray.get(index - i)); } } deleteList.addAll(tempList); } public void addFields(GridView gridView) { int initialSize = fieldArray.size(); ArrayList<NumberField> tempField = new ArrayList<>(); for (NumberField field : fieldArray) { if (field.getState() != NumberField.STATE.USED) { tempField.add(new NumberField(field.getNumber())); } } fieldArray.addAll(tempField); gridView.smoothScrollToPosition(initialSize - 1); notifyDataSetChanged(); findPossibilities(); } private String fieldsToString() { String stringified = ""; for (NumberField field : fieldArray) { stringified += field.stringify() + ","; } stringified = stringified.substring(0, stringified.length() - 1); return stringified; } private void fieldsFromString(String string) { fieldArray = new ArrayList<>(); String[] tempFieldArray = string.split(","); for (String tempField : tempFieldArray) { fieldArray.add(new NumberField(tempField)); } notifyDataSetChanged(); } private void saveState() { dbHelper.saveState(++stateOrder, fieldsToString()); headerCombos.setText(String.valueOf(stateOrder)); } private void won() { stateOrder += 1; activity.gameWon(gameMode, stateOrder); dbHelper.clearDB(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.game_won); builder.setPositiveButton(R.string.confirm_restart_title, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { newGame(); } }); builder.setNegativeButton(R.string.menu, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.finish(); } }); AlertDialog dialog = builder.create(); dialog.setCancelable(false); dialog.show(); } @Override public int getCount() { return fieldArray.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, final View view, ViewGroup viewGroup) { TextView textView; if (view == null) { textView = new TextView(activity); textView.setTextColor(Color.WHITE); textView.setTextSize(25); textView.setGravity(Gravity.CENTER_HORIZONTAL); AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT); textView.setLayoutParams(params); } else { textView = (TextView) view; } textView.setText(String.valueOf(fieldArray.get(i).getNumber())); textView.setAlpha(1); switch (fieldArray.get(i).getState()) { case USED: textView.setAlpha(0.2f); textView.setText(""); case UNUSED: textView.setBackgroundColor(Color.BLACK); break; case SELECTED: textView.setBackgroundColor(Color.BLUE); break; case HINT: textView.setBackgroundColor(Color.GREEN); break; } return textView; } }
app/src/main/java/com/fallenritemonk/ludus/game/GameField.java
package com.fallenritemonk.ludus.game; import android.content.DialogInterface; import android.graphics.Color; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; import com.fallenritemonk.ludus.R; import com.fallenritemonk.ludus.db.DatabaseHelper; import java.util.ArrayList; import java.util.Collections; import java.util.Random; /** * Created by FallenRiteMonk on 9/19/15. */ class GameField extends BaseAdapter { private final GameActivity activity; private final FloatingActionButton addFieldsButton; private final TextView headerCombos; private final GameModeEnum gameMode; private final DatabaseHelper dbHelper; private ArrayList<NumberField> fieldArray; private ArrayList<CombinePos> possibilities = new ArrayList<>(); private int selectedField; private int hint; private int stateOrder; public GameField(final GameActivity activity, FloatingActionButton addFieldsButton, TextView headerCombos, GameModeEnum gameMode, Boolean resume) { this.activity = activity; this.addFieldsButton = addFieldsButton; this.headerCombos = headerCombos; this.gameMode = gameMode; dbHelper = DatabaseHelper.getInstance(activity); if (resume) { resumeGame(); } else { newGame(); } } public void newGame() { fieldArray = new ArrayList<>(); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(2)); fieldArray.add(new NumberField(3)); fieldArray.add(new NumberField(4)); fieldArray.add(new NumberField(5)); fieldArray.add(new NumberField(6)); fieldArray.add(new NumberField(7)); fieldArray.add(new NumberField(8)); fieldArray.add(new NumberField(9)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(2)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(3)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(4)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(5)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(6)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(7)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(8)); fieldArray.add(new NumberField(1)); fieldArray.add(new NumberField(9)); if (gameMode == GameModeEnum.RANDOM) { Collections.shuffle(fieldArray, new Random(System.nanoTime())); } notifyDataSetChanged(); selectedField = -1; hint = -1; stateOrder = -1; findPossibilities(); dbHelper.clearDB(); saveState(); } private void resumeGame() { fieldsFromString(dbHelper.getLastState()); selectedField = -1; hint = -1; stateOrder = dbHelper.getLastStateOrder(); headerCombos.setText(String.valueOf(stateOrder)); findPossibilities(); } private void findPossibilities() { hideHint(); possibilities = new ArrayList<>(); for (int i = 0; i < fieldArray.size() - 1; i++) { if (fieldArray.get(i).getState() == NumberField.STATE.USED) continue; for (int ii = i + 1; ii < fieldArray.size(); ii++) { if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue; if (canBeCombined(i, ii)) { possibilities.add(new CombinePos(i, ii)); } break; } for (int ii = i + 9; ii < fieldArray.size(); ii += 9) { if (fieldArray.get(ii).getState() == NumberField.STATE.USED) continue; if (canBeCombined(i, ii)) { possibilities.add(new CombinePos(i, ii)); } break; } } if (possibilities.size() == 0) addFieldsButton.setVisibility(View.VISIBLE); else addFieldsButton.setVisibility(View.GONE); } private void hideHint() { if (hint != -1) { CombinePos shownHint = possibilities.get(hint); if (shownHint.getId1() < fieldArray.size() && fieldArray.get(shownHint.getId1()).getState() == NumberField.STATE.HINT) { fieldArray.get(shownHint.getId1()).setState(NumberField.STATE.UNUSED); } if (shownHint.getId2() < fieldArray.size() && fieldArray.get(shownHint.getId2()).getState() == NumberField.STATE.HINT) { fieldArray.get(shownHint.getId2()).setState(NumberField.STATE.UNUSED); } hint = -1; } } private boolean canBeCombined(int id1, int id2) { return id1 != id2 && !(fieldArray.get(id1).getNumber() + fieldArray.get(id2).getNumber() != 10 && fieldArray.get(id1).getNumber() != fieldArray.get(id2).getNumber()); } public void hint(GridView gridView) { if (possibilities.size() == 0) return; if (hint >= 0) { fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.UNUSED); fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.UNUSED); } hint = ++hint % possibilities.size(); fieldArray.get(possibilities.get(hint).getId1()).setState(NumberField.STATE.HINT); fieldArray.get(possibilities.get(hint).getId2()).setState(NumberField.STATE.HINT); gridView.smoothScrollToPosition(possibilities.get(hint).getId1()); notifyDataSetChanged(); } public void undo() { if (dbHelper.undo()) { resumeGame(); } } public void clicked(int id) { if (fieldArray.get(id).getState() == NumberField.STATE.USED) return; if (selectedField == -1) { selectedField = id; fieldArray.get(id).setState(NumberField.STATE.SELECTED); notifyDataSetChanged(); } else if (id == selectedField) { fieldArray.get(id).setState(NumberField.STATE.UNUSED); selectedField = -1; notifyDataSetChanged(); } else { combine(id); } } private void combine(int id) { boolean combined = false; for (CombinePos pos : possibilities) { if (pos.equals(new CombinePos(id, selectedField))) { fieldArray.get(id).setState(NumberField.STATE.USED); fieldArray.get(selectedField).setState(NumberField.STATE.USED); if (reduceFields()) { won(); } else { saveState(); findPossibilities(); } selectedField = -1; combined = true; break; } } if (!combined) { fieldArray.get(selectedField).setState(NumberField.STATE.UNUSED); selectedField = -1; } notifyDataSetChanged(); } private boolean reduceFields() { ArrayList<NumberField> deleteList = new ArrayList<>(); int usedCound = 0; for (int i = 0; i < fieldArray.size(); i++) { if (fieldArray.get(i).getState() == NumberField.STATE.USED) { if (++usedCound == 9){ deleteNine(i, deleteList); usedCound = 0; } } else { usedCound = 0; } } fieldArray.removeAll(deleteList); if (usedCound == fieldArray.size()) { fieldArray.clear(); } return fieldArray.isEmpty(); } private void deleteNine(int index, ArrayList<NumberField> deleteList) { ArrayList<NumberField> tempList = new ArrayList<>(); for (int i = 0; i < 9; i++) { if (deleteList.contains(fieldArray.get(index - i))) { return; } else { tempList.add(fieldArray.get(index - i)); } } deleteList.addAll(tempList); } public void addFields(GridView gridView) { int initialSize = fieldArray.size(); ArrayList<NumberField> tempField = new ArrayList<>(); for (NumberField field : fieldArray) { if (field.getState() != NumberField.STATE.USED) { tempField.add(new NumberField(field.getNumber())); } } fieldArray.addAll(tempField); gridView.smoothScrollToPosition(initialSize - 1); notifyDataSetChanged(); findPossibilities(); } private String fieldsToString() { String stringified = ""; for (NumberField field : fieldArray) { stringified += field.stringify() + ","; } stringified = stringified.substring(0, stringified.length() - 1); return stringified; } private void fieldsFromString(String string) { fieldArray = new ArrayList<>(); String[] tempFieldArray = string.split(","); for (String tempField : tempFieldArray) { fieldArray.add(new NumberField(tempField)); } notifyDataSetChanged(); } private void saveState() { dbHelper.saveState(++stateOrder, fieldsToString()); headerCombos.setText(String.valueOf(stateOrder)); } private void won() { stateOrder += 1; activity.gameWon(gameMode, stateOrder); dbHelper.clearDB(); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.game_won); builder.setPositiveButton(R.string.confirm_restart_title, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { newGame(); } }); builder.setNegativeButton(R.string.menu, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { activity.finish(); } }); AlertDialog dialog = builder.create(); dialog.setCancelable(false); dialog.show(); } @Override public int getCount() { return fieldArray.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, final View view, ViewGroup viewGroup) { TextView textView; if (view == null) { textView = new TextView(activity); textView.setTextColor(Color.WHITE); textView.setTextSize(25); textView.setGravity(Gravity.CENTER_HORIZONTAL); AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT); textView.setLayoutParams(params); } else { textView = (TextView) view; } textView.setText(String.valueOf(fieldArray.get(i).getNumber())); textView.setAlpha(1); switch (fieldArray.get(i).getState()) { case USED: textView.setAlpha(0.2f); textView.setText(""); case UNUSED: textView.setBackgroundColor(Color.BLACK); break; case SELECTED: textView.setBackgroundColor(Color.BLUE); break; case HINT: textView.setBackgroundColor(Color.GREEN); break; } return textView; } }
brackets for if
app/src/main/java/com/fallenritemonk/ludus/game/GameField.java
brackets for if
<ide><path>pp/src/main/java/com/fallenritemonk/ludus/game/GameField.java <ide> } <ide> } <ide> <del> if (possibilities.size() == 0) <add> if (possibilities.size() == 0) { <ide> addFieldsButton.setVisibility(View.VISIBLE); <del> else addFieldsButton.setVisibility(View.GONE); <add> } else { <add> addFieldsButton.setVisibility(View.GONE); <add> } <ide> } <ide> <ide> private void hideHint() {
Java
apache-2.0
2d53dba7b13c9adb81b5e9847b1a17204d4a0bd8
0
gravitee-io/graviteeio-access-management,gravitee-io/graviteeio-access-management,gravitee-io/graviteeio-access-management,gravitee-io/graviteeio-access-management,gravitee-io/graviteeio-access-management
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.repository.mongodb.common; import com.mongodb.*; import com.mongodb.connection.*; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.FileInputStream; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class MongoFactory implements FactoryBean<MongoClient> { private final Logger logger = LoggerFactory.getLogger(MongoFactory.class); @Autowired private Environment environment; private final String propertyPrefix; public MongoFactory(String propertyPrefix) { this.propertyPrefix = propertyPrefix + ".mongodb."; } @Override public MongoClient getObject() throws Exception { // Client settings MongoClientSettings.Builder builder = MongoClientSettings.builder(); builder.writeConcern(WriteConcern.ACKNOWLEDGED); CodecRegistry defaultCodecRegistry = MongoClients.getDefaultCodecRegistry(); CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder() .automatic(true) .build()); builder.codecRegistry(fromRegistries(defaultCodecRegistry, pojoCodecRegistry)); // Trying to get the MongoClientURI if uri property is defined String uri = readPropertyValue(propertyPrefix + "uri"); if (uri != null && !uri.isEmpty()) { // The builder can be configured with default options, which may be overridden by options specified in // the URI string. MongoClientSettings settings = builder .applyConnectionString(new ConnectionString(uri)) .build(); return MongoClients.create(settings); } else { // Advanced configuration SocketSettings.Builder socketBuilder = SocketSettings.builder(); ClusterSettings.Builder clusterBuilder = ClusterSettings.builder(); ConnectionPoolSettings.Builder connectionPoolBuilder = ConnectionPoolSettings.builder(); ServerSettings.Builder serverBuilder = ServerSettings.builder(); SslSettings.Builder sslBuilder = SslSettings.builder(); Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 1000); Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class); Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 1000); Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class, true); Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime", Integer.class); Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime", Integer.class); // We do not want to wait for a server Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout", Integer.class, 1000); Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency", Integer.class); String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io"); Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class); Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class); String keystore = readPropertyValue(propertyPrefix + "keystore", String.class); String keystorePassword = readPropertyValue(propertyPrefix + "keystorePassword", String.class); String keyPassword = readPropertyValue(propertyPrefix + "keyPassword", String.class); if (maxWaitTime != null) connectionPoolBuilder.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS); if (connectTimeout != null) socketBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS); if (socketTimeout != null) socketBuilder.readTimeout(socketTimeout, TimeUnit.MILLISECONDS); if (socketKeepAlive != null) socketBuilder.keepAlive(socketKeepAlive); if (maxConnectionLifeTime != null) connectionPoolBuilder.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS); if (maxConnectionIdleTime != null) connectionPoolBuilder.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS); if (minHeartbeatFrequency != null) serverBuilder.minHeartbeatFrequency(minHeartbeatFrequency, TimeUnit.MILLISECONDS); if (description != null) clusterBuilder.description(description); if (heartbeatFrequency != null) serverBuilder.heartbeatFrequency(heartbeatFrequency, TimeUnit.MILLISECONDS); if (sslEnabled != null) sslBuilder.enabled(sslEnabled); if (keystore != null) { try { SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(keystore), keystorePassword.toCharArray()); keyManagerFactory.init(ks, keyPassword.toCharArray()); ctx.init(keyManagerFactory.getKeyManagers(), null, null); sslBuilder.context(ctx); } catch (Exception e) { logger.error(e.getCause().toString()); throw new IllegalStateException("Error creating the keystore for mongodb", e); } } if (serverSelectionTimeout != null) clusterBuilder.serverSelectionTimeout(serverSelectionTimeout, TimeUnit.MILLISECONDS); // credentials option String username = readPropertyValue(propertyPrefix + "username"); String password = readPropertyValue(propertyPrefix + "password"); MongoCredential credentials = null; if (username != null || password != null) { String authSource = readPropertyValue(propertyPrefix + "authSource", String.class, "gravitee-am"); credentials = MongoCredential.createCredential(username, authSource, password.toCharArray()); builder.credential(credentials); } // clustering option List<ServerAddress> seeds; int serversCount = getServersCount(); if (serversCount == 0) { String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost"); int port = readPropertyValue(propertyPrefix + "port", int.class, 27017); seeds = Collections.singletonList(new ServerAddress(host, port)); } else { seeds = new ArrayList<>(serversCount); for (int i = 0; i < serversCount; i++) { seeds.add(buildServerAddress(i)); } } clusterBuilder.hosts(seeds); SocketSettings socketSettings = socketBuilder.build(); ClusterSettings clusterSettings = clusterBuilder.build(); ConnectionPoolSettings connectionPoolSettings = connectionPoolBuilder.build(); ServerSettings serverSettings = serverBuilder.build(); SslSettings sslSettings = sslBuilder.build(); MongoClientSettings settings = builder .applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings)) .applyToSocketSettings(builder1 -> builder1.applySettings(socketSettings)) .applyToConnectionPoolSettings(builder1 -> builder1.applySettings(connectionPoolSettings)) .applyToServerSettings(builder1 -> builder1.applySettings(serverSettings)) .applyToSslSettings(builder1 -> builder1.applySettings(sslSettings)) .build(); return MongoClients.create(settings); } } private int getServersCount() { logger.debug("Looking for MongoDB server configuration..."); boolean found = true; int idx = 0; while (found) { String serverHost = environment.getProperty(propertyPrefix + "servers[" + (idx++) + "].host"); found = (serverHost != null); } return --idx; } private ServerAddress buildServerAddress(int idx) { String host = environment.getProperty(propertyPrefix + "servers[" + idx + "].host"); int port = readPropertyValue(propertyPrefix + "servers[" + idx + "].port", int.class, 27017); return new ServerAddress(host, port); } private String readPropertyValue(String propertyName) { return readPropertyValue(propertyName, String.class, null); } private <T> T readPropertyValue(String propertyName, Class<T> propertyType) { return readPropertyValue(propertyName, propertyType, null); } private <T> T readPropertyValue(String propertyName, Class<T> propertyType, T defaultValue) { T value = environment.getProperty(propertyName, propertyType, defaultValue); logger.debug("Read property {}: {}", propertyName, value); return value; } @Override public Class<?> getObjectType() { return MongoClient.class; } @Override public boolean isSingleton() { return true; } }
gravitee-am-repository/gravitee-am-repository-mongodb/src/main/java/io/gravitee/am/repository/mongodb/common/MongoFactory.java
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.repository.mongodb.common; import com.mongodb.*; import com.mongodb.connection.*; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import org.bson.codecs.configuration.CodecRegistry; import org.bson.codecs.pojo.PojoCodecProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.io.FileInputStream; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class MongoFactory implements FactoryBean<MongoClient> { private final Logger logger = LoggerFactory.getLogger(MongoFactory.class); @Autowired private Environment environment; private final String propertyPrefix; public MongoFactory(String propertyPrefix) { this.propertyPrefix = propertyPrefix + ".mongodb."; } @Override public MongoClient getObject() throws Exception { // Client settings MongoClientSettings.Builder builder = MongoClientSettings.builder(); builder.writeConcern(WriteConcern.ACKNOWLEDGED); CodecRegistry defaultCodecRegistry = MongoClients.getDefaultCodecRegistry(); CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder() .register("io.gravitee.am.repository.mongodb.model", "io.gravitee.am.model") .automatic(true) .build()); builder.codecRegistry(fromRegistries(defaultCodecRegistry, pojoCodecRegistry)); // Trying to get the MongoClientURI if uri property is defined String uri = readPropertyValue(propertyPrefix + "uri"); if (uri != null && !uri.isEmpty()) { // The builder can be configured with default options, which may be overridden by options specified in // the URI string. MongoClientSettings settings = builder .applyConnectionString(new ConnectionString(uri)) .build(); return MongoClients.create(settings); } else { // Advanced configuration SocketSettings.Builder socketBuilder = SocketSettings.builder(); ClusterSettings.Builder clusterBuilder = ClusterSettings.builder(); ConnectionPoolSettings.Builder connectionPoolBuilder = ConnectionPoolSettings.builder(); ServerSettings.Builder serverBuilder = ServerSettings.builder(); SslSettings.Builder sslBuilder = SslSettings.builder(); Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 1000); Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class); Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 1000); Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class, true); Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime", Integer.class); Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime", Integer.class); // We do not want to wait for a server Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout", Integer.class, 1000); Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency", Integer.class); String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io"); Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class); Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class); String keystore = readPropertyValue(propertyPrefix + "keystore", String.class); String keystorePassword = readPropertyValue(propertyPrefix + "keystorePassword", String.class); String keyPassword = readPropertyValue(propertyPrefix + "keyPassword", String.class); if (maxWaitTime != null) connectionPoolBuilder.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS); if (connectTimeout != null) socketBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS); if (socketTimeout != null) socketBuilder.readTimeout(socketTimeout, TimeUnit.MILLISECONDS); if (socketKeepAlive != null) socketBuilder.keepAlive(socketKeepAlive); if (maxConnectionLifeTime != null) connectionPoolBuilder.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS); if (maxConnectionIdleTime != null) connectionPoolBuilder.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS); if (minHeartbeatFrequency != null) serverBuilder.minHeartbeatFrequency(minHeartbeatFrequency, TimeUnit.MILLISECONDS); if (description != null) clusterBuilder.description(description); if (heartbeatFrequency != null) serverBuilder.heartbeatFrequency(heartbeatFrequency, TimeUnit.MILLISECONDS); if (sslEnabled != null) sslBuilder.enabled(sslEnabled); if (keystore != null) { try { SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(keystore), keystorePassword.toCharArray()); keyManagerFactory.init(ks, keyPassword.toCharArray()); ctx.init(keyManagerFactory.getKeyManagers(), null, null); sslBuilder.context(ctx); } catch (Exception e) { logger.error(e.getCause().toString()); throw new IllegalStateException("Error creating the keystore for mongodb", e); } } if (serverSelectionTimeout != null) clusterBuilder.serverSelectionTimeout(serverSelectionTimeout, TimeUnit.MILLISECONDS); // credentials option String username = readPropertyValue(propertyPrefix + "username"); String password = readPropertyValue(propertyPrefix + "password"); MongoCredential credentials = null; if (username != null || password != null) { String authSource = readPropertyValue(propertyPrefix + "authSource", String.class, "gravitee-am"); credentials = MongoCredential.createCredential(username, authSource, password.toCharArray()); builder.credential(credentials); } // clustering option List<ServerAddress> seeds; int serversCount = getServersCount(); if (serversCount == 0) { String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost"); int port = readPropertyValue(propertyPrefix + "port", int.class, 27017); seeds = Collections.singletonList(new ServerAddress(host, port)); } else { seeds = new ArrayList<>(serversCount); for (int i = 0; i < serversCount; i++) { seeds.add(buildServerAddress(i)); } } clusterBuilder.hosts(seeds); SocketSettings socketSettings = socketBuilder.build(); ClusterSettings clusterSettings = clusterBuilder.build(); ConnectionPoolSettings connectionPoolSettings = connectionPoolBuilder.build(); ServerSettings serverSettings = serverBuilder.build(); SslSettings sslSettings = sslBuilder.build(); MongoClientSettings settings = builder .applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings)) .applyToSocketSettings(builder1 -> builder1.applySettings(socketSettings)) .applyToConnectionPoolSettings(builder1 -> builder1.applySettings(connectionPoolSettings)) .applyToServerSettings(builder1 -> builder1.applySettings(serverSettings)) .applyToSslSettings(builder1 -> builder1.applySettings(sslSettings)) .build(); return MongoClients.create(settings); } } private int getServersCount() { logger.debug("Looking for MongoDB server configuration..."); boolean found = true; int idx = 0; while (found) { String serverHost = environment.getProperty(propertyPrefix + "servers[" + (idx++) + "].host"); found = (serverHost != null); } return --idx; } private ServerAddress buildServerAddress(int idx) { String host = environment.getProperty(propertyPrefix + "servers[" + idx + "].host"); int port = readPropertyValue(propertyPrefix + "servers[" + idx + "].port", int.class, 27017); return new ServerAddress(host, port); } private String readPropertyValue(String propertyName) { return readPropertyValue(propertyName, String.class, null); } private <T> T readPropertyValue(String propertyName, Class<T> propertyType) { return readPropertyValue(propertyName, propertyType, null); } private <T> T readPropertyValue(String propertyName, Class<T> propertyType, T defaultValue) { T value = environment.getProperty(propertyName, propertyType, defaultValue); logger.debug("Read property {}: {}", propertyName, value); return value; } @Override public Class<?> getObjectType() { return MongoClient.class; } @Override public boolean isSingleton() { return true; } }
chore(): fix mongodb configuration
gravitee-am-repository/gravitee-am-repository-mongodb/src/main/java/io/gravitee/am/repository/mongodb/common/MongoFactory.java
chore(): fix mongodb configuration
<ide><path>ravitee-am-repository/gravitee-am-repository-mongodb/src/main/java/io/gravitee/am/repository/mongodb/common/MongoFactory.java <ide> <ide> CodecRegistry defaultCodecRegistry = MongoClients.getDefaultCodecRegistry(); <ide> CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder() <del> .register("io.gravitee.am.repository.mongodb.model", "io.gravitee.am.model") <ide> .automatic(true) <ide> .build()); <ide>
Java
mit
50ad667252f693c92bb185cd03849aa3687c00b9
0
LostCodeStudios/gnoPortal
/** * */ package com.lostcodestudios.gnoPortal.gameplay; import java.io.IOException; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.lostcode.javalib.entities.EntityWorld; import com.lostcode.javalib.utils.Convert; import com.lostcode.javalib.utils.SpriteSheet; import com.lostcodestudios.gnoPortal.gameplay.entities.templates.PaddleTemplate; /** * @author william * */ public class PongWorld extends EntityWorld { public PongWorld(InputMultiplexer input, Camera camera, Vector2 gravity) { super(input, camera, gravity); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.lostcode.javalib.entities.EntityWorld#buildSpriteSheet() */ @Override protected void buildSpriteSheet() { try { this.spriteSheet = SpriteSheet.fromXML(Gdx.files.internal("spritesheet.xml")); } catch (IOException e) { e.printStackTrace(); } } @Override protected void buildTemplates() { this.addTemplate("paddle", new PaddleTemplate()); } @Override protected void buildEntities() { this.createEntity("paddle", "left"); } /* (non-Javadoc) * @see com.lostcode.javalib.entities.EntityWorld#getBounds() */ @Override public Rectangle getBounds() { return Convert.pixelsToMeters(new Rectangle(-462/2, -722/2, 462/2, 722/2)); } }
core/src/com/lostcodestudios/gnoPortal/gameplay/PongWorld.java
/** * */ package com.lostcodestudios.gnoPortal.gameplay; import java.io.IOException; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.lostcode.javalib.entities.EntityWorld; import com.lostcode.javalib.utils.Convert; import com.lostcode.javalib.utils.SpriteSheet; /** * @author william * */ public class PongWorld extends EntityWorld { public PongWorld(InputMultiplexer input, Camera camera, Vector2 gravity) { super(input, camera, gravity); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see com.lostcode.javalib.entities.EntityWorld#buildSpriteSheet() */ @Override protected void buildSpriteSheet() { try { this.spriteSheet = SpriteSheet.fromXML(Gdx.files.internal("spritesheet.xml")); } catch (IOException e) { e.printStackTrace(); } } /* (non-Javadoc) * @see com.lostcode.javalib.entities.EntityWorld#getBounds() */ @Override public Rectangle getBounds() { return Convert.pixelsToMeters(new Rectangle(-462/2, -722/2, 462/2, 722/2)); } }
updating libgdx libs
core/src/com/lostcodestudios/gnoPortal/gameplay/PongWorld.java
updating libgdx libs
<ide><path>ore/src/com/lostcodestudios/gnoPortal/gameplay/PongWorld.java <ide> import com.lostcode.javalib.entities.EntityWorld; <ide> import com.lostcode.javalib.utils.Convert; <ide> import com.lostcode.javalib.utils.SpriteSheet; <add>import com.lostcodestudios.gnoPortal.gameplay.entities.templates.PaddleTemplate; <ide> <ide> /** <ide> * @author william <ide> } <ide> } <ide> <add> @Override <add> protected void buildTemplates() { <add> this.addTemplate("paddle", new PaddleTemplate()); <add> } <add> <add> @Override <add> protected void buildEntities() { <add> this.createEntity("paddle", "left"); <add> } <add> <ide> /* (non-Javadoc) <ide> * @see com.lostcode.javalib.entities.EntityWorld#getBounds() <ide> */
Java
apache-2.0
3f93fd7d7435ad3e814acfd0f045619d943998d4
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
/* * Copyright (C) 2009 University of Washington * * 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.odk.collect.android.utilities; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.util.Log; import org.javarosa.core.io.StreamsUtil; import org.javarosa.xform.parse.XFormParseException; import org.javarosa.xform.parse.XFormParser; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; import org.odk.collect.android.widgets.ImageWidget; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.channels.FileChannel; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * Static methods used for common file operations. * * @author Carl Hartung ([email protected]) */ public class FileUtils { private final static String t = "FileUtils"; // Used to validate and display valid form names. public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml"; //highest allowable file size without warning public static int WARNING_SIZE = 3000; public static boolean createFolder(String path) { boolean made = true; File dir = new File(path); if (!dir.exists()) { made = dir.mkdirs(); } return made; } public static byte[] getFileAsBytes(File file) { return getFileAsBytes(file, null); } public static byte[] getFileAsBytes(File file, SecretKeySpec symetricKey) { byte[] bytes = null; InputStream is = null; try { is = new FileInputStream(file); if(symetricKey != null) { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, symetricKey); is = new CipherInputStream(is, cipher); } //CTS - Removed a lot of weird checks here. file size < max int? We're shoving this //form into a _Byte array_, I don't think there's a lot of concern than 2GB of data //are gonna sneak by. ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { StreamsUtil.writeFromInputToOutput(is, baos); bytes = baos.toByteArray(); } catch (IOException e) { Log.e(t, "Cannot read " + file.getName()); e.printStackTrace(); return null; } //CTS - Removed the byte array length check here. Plenty of //files are smaller than their contents (padded encryption data, etc), //so you can't actually know that's correct. We should be relying on the //methods we use to read data to make sure it's all coming out. return bytes; } catch (FileNotFoundException e) { Log.e(t, "Cannot find " + file.getName()); e.printStackTrace(); return null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (InvalidKeyException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { // Close the input stream try { is.close(); } catch (IOException e) { Log.e(t, "Cannot close input stream for " + file.getName()); e.printStackTrace(); return null; } } } public static String getMd5Hash(File file) { try { // CTS (6/15/2010) : stream file through digest instead of handing it the byte[] MessageDigest md = MessageDigest.getInstance("MD5"); int chunkSize = 256; byte[] chunk = new byte[chunkSize]; // Get the size of the file long lLength = file.length(); if (lLength > Integer.MAX_VALUE) { Log.e(t, "File " + file.getName() + "is too large"); return null; } int length = (int) lLength; InputStream is = null; is = new FileInputStream(file); int l = 0; for (l = 0; l + chunkSize < length; l += chunkSize) { is.read(chunk, 0, chunkSize); md.update(chunk, 0, chunkSize); } int remaining = length - l; if (remaining > 0) { is.read(chunk, 0, remaining); md.update(chunk, 0, remaining); } byte[] messageDigest = md.digest(); BigInteger number = new BigInteger(1, messageDigest); String md5 = number.toString(16); while (md5.length() < 32) md5 = "0" + md5; is.close(); return md5; } catch (NoSuchAlgorithmException e) { Log.e("MD5", e.getMessage()); return null; } catch (FileNotFoundException e) { Log.e("No Cache File", e.getMessage()); return null; } catch (IOException e) { Log.e("Problem reading file", e.getMessage()); return null; } } public static String getExtension(String filePath) { if (filePath.contains(".")) { return last(filePath.split("\\.")); } return ""; } /** * Get the last element of a String array. */ private static String last(String[] strings) { return strings[strings.length - 1]; } /** * Attempts to scale down an image file based on the max dimension given. If at least one of * the dimensions of the original image exceeds that maximum, then make the larger side's * dimension equal to the max dimension, and scale down the smaller side such that the * original aspect ratio is maintained */ public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; String extension = getExtension(originalImage.getAbsolutePath()); ImageWidget.ImageType type = ImageWidget.ImageType.fromExtension(extension); if (type == null) { // The selected image is not of a type that can be decoded to or from a bitmap Log.i(t, "Could not scale image " + originalImage.getAbsolutePath() + " due to incompatible extension"); return false; } // Create a bitmap out of the image file to see if we need to scale it down Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { // If the larger dimension exceeds our max dimension, scale down accordingly double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } // Write this scaled bitmap to the final file location FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); bitmap.compress(type.getCompressFormat(), 100, out); scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; } public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) { // Determine dimensions of original image BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(f.getAbsolutePath(), o); int imageHeight = o.outHeight; int imageWidth = o.outWidth; // Get a scale-down factor -- Powers of 2 work faster according to the docs, but we're // just doing closest size that still fills the screen int heightScale = Math.round((float)imageHeight / screenHeight); int widthScale = Math.round((float)imageWidth / screenWidth); int scale = Math.max(widthScale, heightScale); if (scale == 0) { // Rounding could possibly have resulted in a scale factor of 0, which is invalid scale = 1; } return performSafeScaleDown(f, scale, 0); } /** * Returns a scaled-down bitmap for the given image file, progressively increasing the * scale-down factor by 1 until allocating memory for the bitmap does not cause an OOM error */ private static Bitmap performSafeScaleDown(File f, int scale, int depth) { if (depth == 8) { // Limit the number of recursive calls return null; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = scale; try { return BitmapFactory.decodeFile(f.getAbsolutePath(), options); } catch (OutOfMemoryError e) { return performSafeScaleDown(f, ++scale, ++depth); } } /** * Copies from sourceFile to destFile (either a directory, or a path * to the new file) * * @param sourceFile A file pointer to a file on the file system * @param destFile Either a file or directory. If a directory, the * file name will be taken from the source file */ public static void copyFile(File sourceFile, File destFile) { if (sourceFile.exists()) { if(destFile.isDirectory()) { destFile = new File(destFile, sourceFile.getName()); } FileChannel src; try { src = new FileInputStream(sourceFile).getChannel(); FileChannel dst = new FileOutputStream(destFile).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } catch (FileNotFoundException e) { Log.e(t, "FileNotFoundExeception while copying audio"); e.printStackTrace(); } catch (IOException e) { Log.e(t, "IOExeception while copying audio"); e.printStackTrace(); } } else { Log.e(t, "Source file does not exist: " + sourceFile.getAbsolutePath()); } } public static String FORMID = "formid"; public static String UI = "uiversion"; public static String MODEL = "modelversion"; public static String TITLE = "title"; public static String SUBMISSIONURI = "submission"; public static String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; public static HashMap<String, String> parseXML(File xmlFile) { HashMap<String, String> fields = new HashMap<String, String>(); InputStream is; try { is = new FileInputStream(xmlFile); } catch (FileNotFoundException e1) { throw new IllegalStateException(e1); } InputStreamReader isr; try { isr = new InputStreamReader(is, "UTF-8"); } catch (UnsupportedEncodingException uee) { Log.w(t, "UTF 8 encoding unavailable, trying default encoding"); isr = new InputStreamReader(is); } if (isr != null) { Document doc; try { doc = XFormParser.getXMLDocument(isr); } catch(IOException e) { e.printStackTrace(); throw new XFormParseException("IO Exception during form parsing: " + e.getMessage()); } finally { try { isr.close(); } catch (IOException e) { Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader"); e.printStackTrace(); } } String xforms = "http://www.w3.org/2002/xforms"; String html = doc.getRootElement().getNamespace(); Element head = doc.getRootElement().getElement(html, "head"); Element title = head.getElement(html, "title"); if (title != null) { fields.put(TITLE, XFormParser.getXMLText(title, true)); } Element model = getChildElement(head, "model"); Element cur = getChildElement(model,"instance"); int idx = cur.getChildCount(); int i; for (i = 0; i < idx; ++i) { if (cur.isText(i)) continue; if (cur.getType(i) == Node.ELEMENT) { break; } } if (i < idx) { cur = cur.getElement(i); // this is the first data element String id = cur.getAttributeValue(null, "id"); String xmlns = cur.getNamespace(); String modelVersion = cur.getAttributeValue(null, "version"); String uiVersion = cur.getAttributeValue(null, "uiVersion"); fields.put(FORMID, (id == null) ? xmlns : id); fields.put(MODEL, (modelVersion == null) ? null : modelVersion); fields.put(UI, (uiVersion == null) ? null : uiVersion); } else { throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed"); } try { Element submission = model.getElement(xforms, "submission"); String submissionUri = submission.getAttributeValue(null, "action"); fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri); String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey"); fields.put(BASE64_RSA_PUBLIC_KEY, (base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0) ? null : base64RsaPublicKey.trim()); } catch (Exception e) { Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element"); // and that's totally fine. } } return fields; } // needed because element.getelement fails when there are attributes private static Element getChildElement(Element parent, String childName) { Element e = null; int c = parent.getChildCount(); int i = 0; for (i = 0; i < c; i++) { if (parent.getType(i) == Node.ELEMENT) { if (parent.getElement(i).getName().equalsIgnoreCase(childName)) { return parent.getElement(i); } } } return e; } public static boolean isFileOversized(File mf){ double length = getFileSize(mf); return length > WARNING_SIZE; } public static double getFileSize(File mf){ return mf.length()/(1024); } /* * @param context The context. * @param uri The Uri to query. * @author paulburke * * Get's the correct path for different Android API levels * */ @SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } }
app/src/org/odk/collect/android/utilities/FileUtils.java
/* * Copyright (C) 2009 University of Washington * * 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.odk.collect.android.utilities; import android.annotation.SuppressLint; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; import android.util.Log; import org.javarosa.core.io.StreamsUtil; import org.javarosa.xform.parse.XFormParseException; import org.javarosa.xform.parse.XFormParser; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.kxml2.kdom.Node; import org.odk.collect.android.widgets.ImageWidget; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.nio.channels.FileChannel; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * Static methods used for common file operations. * * @author Carl Hartung ([email protected]) */ public class FileUtils { private final static String t = "FileUtils"; // Used to validate and display valid form names. public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml"; //highest allowable file size without warning public static int WARNING_SIZE = 3000; public static boolean createFolder(String path) { boolean made = true; File dir = new File(path); if (!dir.exists()) { made = dir.mkdirs(); } return made; } public static byte[] getFileAsBytes(File file) { return getFileAsBytes(file, null); } public static byte[] getFileAsBytes(File file, SecretKeySpec symetricKey) { byte[] bytes = null; InputStream is = null; try { is = new FileInputStream(file); if(symetricKey != null) { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, symetricKey); is = new CipherInputStream(is, cipher); } //CTS - Removed a lot of weird checks here. file size < max int? We're shoving this //form into a _Byte array_, I don't think there's a lot of concern than 2GB of data //are gonna sneak by. ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { StreamsUtil.writeFromInputToOutput(is, baos); bytes = baos.toByteArray(); } catch (IOException e) { Log.e(t, "Cannot read " + file.getName()); e.printStackTrace(); return null; } //CTS - Removed the byte array length check here. Plenty of //files are smaller than their contents (padded encryption data, etc), //so you can't actually know that's correct. We should be relying on the //methods we use to read data to make sure it's all coming out. return bytes; } catch (FileNotFoundException e) { Log.e(t, "Cannot find " + file.getName()); e.printStackTrace(); return null; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (NoSuchPaddingException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (InvalidKeyException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { // Close the input stream try { is.close(); } catch (IOException e) { Log.e(t, "Cannot close input stream for " + file.getName()); e.printStackTrace(); return null; } } } public static String getMd5Hash(File file) { try { // CTS (6/15/2010) : stream file through digest instead of handing it the byte[] MessageDigest md = MessageDigest.getInstance("MD5"); int chunkSize = 256; byte[] chunk = new byte[chunkSize]; // Get the size of the file long lLength = file.length(); if (lLength > Integer.MAX_VALUE) { Log.e(t, "File " + file.getName() + "is too large"); return null; } int length = (int) lLength; InputStream is = null; is = new FileInputStream(file); int l = 0; for (l = 0; l + chunkSize < length; l += chunkSize) { is.read(chunk, 0, chunkSize); md.update(chunk, 0, chunkSize); } int remaining = length - l; if (remaining > 0) { is.read(chunk, 0, remaining); md.update(chunk, 0, remaining); } byte[] messageDigest = md.digest(); BigInteger number = new BigInteger(1, messageDigest); String md5 = number.toString(16); while (md5.length() < 32) md5 = "0" + md5; is.close(); return md5; } catch (NoSuchAlgorithmException e) { Log.e("MD5", e.getMessage()); return null; } catch (FileNotFoundException e) { Log.e("No Cache File", e.getMessage()); return null; } catch (IOException e) { Log.e("Problem reading file", e.getMessage()); return null; } } public static String getExtension(String filePath) { if (filePath.contains(".")) { return last(filePath.split("\\.")); } return ""; } /** * Get the last element of a String array. */ private static String last(String[] strings) { return strings[strings.length - 1]; } /** * Attempts to scale down an image file based on the max dimension given. If at least one of * the dimensions of the original image exceeds that maximum, then make the larger side's * dimension equal to the max dimension, and scale down the smaller side such that the * original aspect ratio is maintained */ public static boolean scaleImage(File originalImage, String finalFilePath, int maxDimen) { boolean scaledImage = false; String extension = getExtension(originalImage.getAbsolutePath()); ImageWidget.ImageType type = ImageWidget.ImageType.fromExtension(extension); if (type == null) { // The selected image is not of a type that can be decoded to or from a bitmap Log.i(t, "Could not scale image " + originalImage.getAbsolutePath() + " due to incompatible extension"); return false; } // Create a bitmap out of the image file to see if we need to scale it down Bitmap bitmap = BitmapFactory.decodeFile(originalImage.getAbsolutePath()); int height = bitmap.getHeight(); int width = bitmap.getWidth(); int largerDimen = Math.max(height, width); int smallerDimen = Math.min(height, width); if (largerDimen > maxDimen) { // If the larger dimension exceeds our max dimension, scale down accordingly double aspectRatio = ((double) smallerDimen) / largerDimen; largerDimen = maxDimen; smallerDimen = (int) Math.floor(maxDimen * aspectRatio); if (width > height) { bitmap = Bitmap.createScaledBitmap(bitmap, largerDimen, smallerDimen, false); } else { bitmap = Bitmap.createScaledBitmap(bitmap, smallerDimen, largerDimen, false); } // Write this scaled bitmap to the final file location FileOutputStream out = null; try { out = new FileOutputStream(finalFilePath); bitmap.compress(type.getCompressFormat(), 100, out); scaledImage = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } return scaledImage; } public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) { // Determine dimensions of original image BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(f.getAbsolutePath(), o); int imageHeight = o.outHeight; int imageWidth = o.outWidth; // Get a scale-down factor -- Powers of 2 work faster according to the docs, but we're // just doing closest size that still fills the screen int heightScale = Math.round((float)imageHeight / screenHeight); int widthScale = Math.round((float)imageWidth / screenWidth); int scale = Math.max(widthScale, heightScale); if (scale == 0) { // Rounding could possibly have resulted in a scale factor of 0, which is invalid scale = 1; } return performSafeScaleDown(f, scale); } /** * Returns a scaled-down bitmap for the given image file, progressively increasing the * scale-down factor by 1 until allocating memory for the bitmap does not cause an OOM error */ private static Bitmap performSafeScaleDown(File f, int scale) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = scale; try { return BitmapFactory.decodeFile(f.getAbsolutePath(), options); } catch (OutOfMemoryError e) { scale++; return performSafeScaleDown(f, scale); } } /** * Copies from sourceFile to destFile (either a directory, or a path * to the new file) * * @param sourceFile A file pointer to a file on the file system * @param destFile Either a file or directory. If a directory, the * file name will be taken from the source file */ public static void copyFile(File sourceFile, File destFile) { if (sourceFile.exists()) { if(destFile.isDirectory()) { destFile = new File(destFile, sourceFile.getName()); } FileChannel src; try { src = new FileInputStream(sourceFile).getChannel(); FileChannel dst = new FileOutputStream(destFile).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } catch (FileNotFoundException e) { Log.e(t, "FileNotFoundExeception while copying audio"); e.printStackTrace(); } catch (IOException e) { Log.e(t, "IOExeception while copying audio"); e.printStackTrace(); } } else { Log.e(t, "Source file does not exist: " + sourceFile.getAbsolutePath()); } } public static String FORMID = "formid"; public static String UI = "uiversion"; public static String MODEL = "modelversion"; public static String TITLE = "title"; public static String SUBMISSIONURI = "submission"; public static String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; public static HashMap<String, String> parseXML(File xmlFile) { HashMap<String, String> fields = new HashMap<String, String>(); InputStream is; try { is = new FileInputStream(xmlFile); } catch (FileNotFoundException e1) { throw new IllegalStateException(e1); } InputStreamReader isr; try { isr = new InputStreamReader(is, "UTF-8"); } catch (UnsupportedEncodingException uee) { Log.w(t, "UTF 8 encoding unavailable, trying default encoding"); isr = new InputStreamReader(is); } if (isr != null) { Document doc; try { doc = XFormParser.getXMLDocument(isr); } catch(IOException e) { e.printStackTrace(); throw new XFormParseException("IO Exception during form parsing: " + e.getMessage()); } finally { try { isr.close(); } catch (IOException e) { Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader"); e.printStackTrace(); } } String xforms = "http://www.w3.org/2002/xforms"; String html = doc.getRootElement().getNamespace(); Element head = doc.getRootElement().getElement(html, "head"); Element title = head.getElement(html, "title"); if (title != null) { fields.put(TITLE, XFormParser.getXMLText(title, true)); } Element model = getChildElement(head, "model"); Element cur = getChildElement(model,"instance"); int idx = cur.getChildCount(); int i; for (i = 0; i < idx; ++i) { if (cur.isText(i)) continue; if (cur.getType(i) == Node.ELEMENT) { break; } } if (i < idx) { cur = cur.getElement(i); // this is the first data element String id = cur.getAttributeValue(null, "id"); String xmlns = cur.getNamespace(); String modelVersion = cur.getAttributeValue(null, "version"); String uiVersion = cur.getAttributeValue(null, "uiVersion"); fields.put(FORMID, (id == null) ? xmlns : id); fields.put(MODEL, (modelVersion == null) ? null : modelVersion); fields.put(UI, (uiVersion == null) ? null : uiVersion); } else { throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed"); } try { Element submission = model.getElement(xforms, "submission"); String submissionUri = submission.getAttributeValue(null, "action"); fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri); String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey"); fields.put(BASE64_RSA_PUBLIC_KEY, (base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0) ? null : base64RsaPublicKey.trim()); } catch (Exception e) { Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element"); // and that's totally fine. } } return fields; } // needed because element.getelement fails when there are attributes private static Element getChildElement(Element parent, String childName) { Element e = null; int c = parent.getChildCount(); int i = 0; for (i = 0; i < c; i++) { if (parent.getType(i) == Node.ELEMENT) { if (parent.getElement(i).getName().equalsIgnoreCase(childName)) { return parent.getElement(i); } } } return e; } public static boolean isFileOversized(File mf){ double length = getFileSize(mf); return length > WARNING_SIZE; } public static double getFileSize(File mf){ return mf.length()/(1024); } /* * @param context The context. * @param uri The Uri to query. * @author paulburke * * Get's the correct path for different Android API levels * */ @SuppressLint("NewApi") public static String getPath(final Context context, final Uri uri) { final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context The context. * @param uri The Uri to query. * @param selection (Optional) Filter used in the query. * @param selectionArgs (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } /** * @param uri The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } }
limit recursion depth
app/src/org/odk/collect/android/utilities/FileUtils.java
limit recursion depth
<ide><path>pp/src/org/odk/collect/android/utilities/FileUtils.java <ide> scale = 1; <ide> } <ide> <del> return performSafeScaleDown(f, scale); <add> return performSafeScaleDown(f, scale, 0); <ide> } <ide> <ide> /** <ide> * Returns a scaled-down bitmap for the given image file, progressively increasing the <ide> * scale-down factor by 1 until allocating memory for the bitmap does not cause an OOM error <ide> */ <del> private static Bitmap performSafeScaleDown(File f, int scale) { <add> private static Bitmap performSafeScaleDown(File f, int scale, int depth) { <add> if (depth == 8) { <add> // Limit the number of recursive calls <add> return null; <add> } <ide> BitmapFactory.Options options = new BitmapFactory.Options(); <ide> options.inSampleSize = scale; <ide> try { <ide> return BitmapFactory.decodeFile(f.getAbsolutePath(), options); <ide> } catch (OutOfMemoryError e) { <del> scale++; <del> return performSafeScaleDown(f, scale); <add> return performSafeScaleDown(f, ++scale, ++depth); <ide> } <ide> } <ide>
Java
mit
b7d68341e41319a8ae2371a4f4f5b6e58c318acc
0
sake/bouncycastle-java
package org.bouncycastle.asn1.x509; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.Strings; /** * <pre> * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type OBJECT IDENTIFIER, * value ANY } * </pre> */ public class X509Name extends ASN1Encodable { /** * country code - StringType(SIZE(2)) */ public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6"); /** * organization - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10"); /** * organizational unit name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11"); /** * Title */ public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12"); /** * common name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5"); /** * street - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier STREET = new DERObjectIdentifier("2.5.4.9"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SERIALNUMBER = SN; /** * locality name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7"); /** * state, or province name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8"); /** * Naming attributes of type X520name */ public static final DERObjectIdentifier SURNAME = new DERObjectIdentifier("2.5.4.4"); public static final DERObjectIdentifier GIVENNAME = new DERObjectIdentifier("2.5.4.42"); public static final DERObjectIdentifier INITIALS = new DERObjectIdentifier("2.5.4.43"); public static final DERObjectIdentifier GENERATION = new DERObjectIdentifier("2.5.4.44"); public static final DERObjectIdentifier UNIQUE_IDENTIFIER = new DERObjectIdentifier("2.5.4.45"); /** * businessCategory - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier BUSINESS_CATEGORY = new DERObjectIdentifier( "2.5.4.15"); /** * postalCode - DirectoryString(SIZE(1..40) */ public static final DERObjectIdentifier POSTAL_CODE = new DERObjectIdentifier( "2.5.4.17"); /** * dnQualifier - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier DN_QUALIFIER = new DERObjectIdentifier( "2.5.4.46"); /** * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier PSEUDONYM = new DERObjectIdentifier( "2.5.4.65"); /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ public static final DERObjectIdentifier DATE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.1"); /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier PLACE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.2"); /** * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ public static final DERObjectIdentifier GENDER = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.3"); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_CITIZENSHIP = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.4"); /** * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_RESIDENCE = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.5"); /** * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier NAME_AT_BIRTH = new DERObjectIdentifier("1.3.36.8.3.14"); /** * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF * DirectoryString(SIZE(1..30)) */ public static final DERObjectIdentifier POSTAL_ADDRESS = new DERObjectIdentifier( "2.5.4.16"); /** * Email address (RSA PKCS#9 extension) - IA5String. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. */ public static final DERObjectIdentifier EmailAddress = PKCSObjectIdentifiers.pkcs_9_at_emailAddress; /** * more from PKCS#9 */ public static final DERObjectIdentifier UnstructuredName = PKCSObjectIdentifiers.pkcs_9_at_unstructuredName; public static final DERObjectIdentifier UnstructuredAddress = PKCSObjectIdentifiers.pkcs_9_at_unstructuredAddress; /** * email address in Verisign certificates */ public static final DERObjectIdentifier E = EmailAddress; /* * others... */ public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25"); /** * LDAP User id. */ public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1"); /** * look up table translating OID values into their common symbols - this static is scheduled for deletion */ public static Hashtable OIDLookUp = new Hashtable(); /** * determines whether or not strings should be processed and printed * from back to front. */ public static boolean DefaultReverse = false; /** * default look up table translating OID values into their common symbols following * the convention in RFC 2253 with a few extras */ public static Hashtable DefaultSymbols = OIDLookUp; /** * look up table translating OID values into their common symbols following the convention in RFC 2253 * */ public static Hashtable RFC2253Symbols = new Hashtable(); /** * look up table translating OID values into their common symbols following the convention in RFC 1779 * */ public static Hashtable RFC1779Symbols = new Hashtable(); /** * look up table translating string values into their OIDS - * this static is scheduled for deletion */ public static Hashtable SymbolLookUp = new Hashtable(); /** * look up table translating common symbols into their OIDS. */ public static Hashtable DefaultLookUp = SymbolLookUp; static { DefaultSymbols.put(C, "C"); DefaultSymbols.put(O, "O"); DefaultSymbols.put(T, "T"); DefaultSymbols.put(OU, "OU"); DefaultSymbols.put(CN, "CN"); DefaultSymbols.put(L, "L"); DefaultSymbols.put(ST, "ST"); DefaultSymbols.put(SN, "SN"); DefaultSymbols.put(EmailAddress, "E"); DefaultSymbols.put(DC, "DC"); DefaultSymbols.put(UID, "UID"); DefaultSymbols.put(STREET, "STREET"); DefaultSymbols.put(SURNAME, "SURNAME"); DefaultSymbols.put(GIVENNAME, "GIVENNAME"); DefaultSymbols.put(INITIALS, "INITIALS"); DefaultSymbols.put(GENERATION, "GENERATION"); DefaultSymbols.put(UnstructuredAddress, "unstructuredAddress"); DefaultSymbols.put(UnstructuredName, "unstructuredName"); DefaultSymbols.put(UNIQUE_IDENTIFIER, "UniqueIdentifier"); DefaultSymbols.put(DN_QUALIFIER, "DN"); DefaultSymbols.put(PSEUDONYM, "Pseudonym"); DefaultSymbols.put(POSTAL_ADDRESS, "PostalAddress"); DefaultSymbols.put(NAME_AT_BIRTH, "NameAtBirth"); DefaultSymbols.put(COUNTRY_OF_CITIZENSHIP, "CountryOfCitizenship"); DefaultSymbols.put(COUNTRY_OF_RESIDENCE, "CountryOfResidence"); DefaultSymbols.put(GENDER, "Gender"); DefaultSymbols.put(PLACE_OF_BIRTH, "PlaceOfBirth"); DefaultSymbols.put(DATE_OF_BIRTH, "DateOfBirth"); DefaultSymbols.put(POSTAL_CODE, "PostalCode"); DefaultSymbols.put(BUSINESS_CATEGORY, "BusinessCategory"); RFC2253Symbols.put(C, "C"); RFC2253Symbols.put(O, "O"); RFC2253Symbols.put(OU, "OU"); RFC2253Symbols.put(CN, "CN"); RFC2253Symbols.put(L, "L"); RFC2253Symbols.put(ST, "ST"); RFC2253Symbols.put(STREET, "STREET"); RFC2253Symbols.put(DC, "DC"); RFC2253Symbols.put(UID, "UID"); RFC1779Symbols.put(C, "C"); RFC1779Symbols.put(O, "O"); RFC1779Symbols.put(OU, "OU"); RFC1779Symbols.put(CN, "CN"); RFC1779Symbols.put(L, "L"); RFC1779Symbols.put(ST, "ST"); RFC1779Symbols.put(STREET, "STREET"); DefaultLookUp.put("c", C); DefaultLookUp.put("o", O); DefaultLookUp.put("t", T); DefaultLookUp.put("ou", OU); DefaultLookUp.put("cn", CN); DefaultLookUp.put("l", L); DefaultLookUp.put("st", ST); DefaultLookUp.put("sn", SN); DefaultLookUp.put("serialnumber", SN); DefaultLookUp.put("street", STREET); DefaultLookUp.put("emailaddress", E); DefaultLookUp.put("dc", DC); DefaultLookUp.put("e", E); DefaultLookUp.put("uid", UID); DefaultLookUp.put("surname", SURNAME); DefaultLookUp.put("givenname", GIVENNAME); DefaultLookUp.put("initials", INITIALS); DefaultLookUp.put("generation", GENERATION); DefaultLookUp.put("unstructuredaddress", UnstructuredAddress); DefaultLookUp.put("unstructuredname", UnstructuredName); DefaultLookUp.put("uniqueidentifier", UNIQUE_IDENTIFIER); DefaultLookUp.put("dn", DN_QUALIFIER); DefaultLookUp.put("pseudonym", PSEUDONYM); DefaultLookUp.put("postaladdress", POSTAL_ADDRESS); DefaultLookUp.put("nameofbirth", NAME_AT_BIRTH); DefaultLookUp.put("countryofcitizenship", COUNTRY_OF_CITIZENSHIP); DefaultLookUp.put("countryofresidence", COUNTRY_OF_RESIDENCE); DefaultLookUp.put("gender", GENDER); DefaultLookUp.put("placeofbirth", PLACE_OF_BIRTH); DefaultLookUp.put("dateofbirth", DATE_OF_BIRTH); DefaultLookUp.put("postalcode", POSTAL_CODE); DefaultLookUp.put("businesscategory", BUSINESS_CATEGORY); } private X509NameEntryConverter converter = null; private Vector ordering = new Vector(); private Vector values = new Vector(); private Vector added = new Vector(); private ASN1Sequence seq; /** * Return a X509Name based on the passed in tagged object. * * @param obj tag object holding name. * @param explicit true if explicitly tagged false otherwise. * @return the X509Name */ public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } public static X509Name getInstance( Object obj) { if (obj == null || obj instanceof X509Name) { return (X509Name)obj; } else if (obj instanceof ASN1Sequence) { return new X509Name((ASN1Sequence)obj); } throw new IllegalArgumentException("unknown object in factory \"" + obj.getClass().getName()+"\""); } /** * Constructor from ASN1Sequence * * the principal will be a list of constructed sets, each containing an (OID, String) pair. */ public X509Name( ASN1Sequence seq) { this.seq = seq; Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { ASN1Set set = (ASN1Set)e.nextElement(); for (int i = 0; i < set.size(); i++) { ASN1Sequence s = (ASN1Sequence)set.getObjectAt(i); ordering.addElement(s.getObjectAt(0)); DEREncodable value = s.getObjectAt(1); if (value instanceof DERString) { values.addElement(((DERString)value).getString()); } else { values.addElement("#" + bytesToString(Hex.encode(value.getDERObject().getDEREncoded()))); } added.addElement(Boolean.valueOf(i != 0)); } } } /** * constructor from a table of attributes. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. * <p> * <b>Note:</b> if the name you are trying to generate should be * following a specific ordering, you should use the constructor * with the ordering specified below. */ public X509Name( Hashtable attributes) { this(null, attributes); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. */ public X509Name( Vector ordering, Hashtable attributes) { this(ordering, attributes, new X509DefaultEntryConverter()); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector ordering, Hashtable attributes, X509DefaultEntryConverter converter) { this.converter = converter; if (ordering != null) { for (int i = 0; i != ordering.size(); i++) { this.ordering.addElement(ordering.elementAt(i)); this.added.addElement(Boolean.FALSE); } } else { Enumeration e = attributes.keys(); while (e.hasMoreElements()) { this.ordering.addElement(e.nextElement()); this.added.addElement(Boolean.FALSE); } } for (int i = 0; i != this.ordering.size(); i++) { DERObjectIdentifier oid = (DERObjectIdentifier)this.ordering.elementAt(i); if (attributes.get(oid) == null) { throw new IllegalArgumentException("No attribute for object id - " + oid.getId() + " - passed to distinguished name"); } this.values.addElement(attributes.get(oid)); // copy the hash table } } /** * Takes two vectors one of the oids and the other of the values. */ public X509Name( Vector oids, Vector values) { this(oids, values, new X509DefaultEntryConverter()); } /** * Takes two vectors one of the oids and the other of the values. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector oids, Vector values, X509NameEntryConverter converter) { this.converter = converter; if (oids.size() != values.size()) { throw new IllegalArgumentException("oids vector must be same length as values."); } for (int i = 0; i < oids.size(); i++) { this.ordering.addElement(oids.elementAt(i)); this.values.addElement(values.elementAt(i)); this.added.addElement(Boolean.FALSE); } } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. */ public X509Name( String dirName) { this(DefaultReverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. */ public X509Name( String dirName, X509NameEntryConverter converter) { this(DefaultReverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. If reverse * is true, create the encoded version of the sequence starting from the * last element in the string. */ public X509Name( boolean reverse, String dirName) { this(reverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. If reverse is true the ASN.1 sequence representing the DN will * be built by starting at the end of the string, rather than the start. */ public X509Name( boolean reverse, String dirName, X509NameEntryConverter converter) { this(reverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. * <br> * If reverse is true, create the encoded version of the sequence * starting from the last element in the string. * @param reverse true if we should start scanning from the end (RFC 2553). * @param lookUp table of names and their oids. * @param dirName the X.500 string to be parsed. */ public X509Name( boolean reverse, Hashtable lookUp, String dirName) { this(reverse, lookUp, dirName, new X509DefaultEntryConverter()); } private DERObjectIdentifier decodeOID( String name, Hashtable lookUp) { if (Strings.toUpperCase(name).startsWith("OID.")) { return new DERObjectIdentifier(name.substring(4)); } else if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { return new DERObjectIdentifier(name); } DERObjectIdentifier oid = (DERObjectIdentifier)lookUp.get(Strings.toLowerCase(name)); if (oid == null) { throw new IllegalArgumentException("Unknown object id - " + name + " - passed to distinguished name"); } return oid; } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. The passed in converter is used to convert the * string values to the right of each equals sign to their ASN.1 counterparts. * <br> * @param reverse true if we should start scanning from the end, false otherwise. * @param lookUp table of names and oids. * @param dirName the string dirName * @param converter the converter to convert string values into their ASN.1 equivalents */ public X509Name( boolean reverse, Hashtable lookUp, String dirName, X509NameEntryConverter converter) { this.converter = converter; X509NameTokenizer nTok = new X509NameTokenizer(dirName); while (nTok.hasMoreTokens()) { String token = nTok.nextToken(); int index = token.indexOf('='); if (index == -1) { throw new IllegalArgumentException("badly formated directory string"); } String name = token.substring(0, index); String value = token.substring(index + 1); DERObjectIdentifier oid = decodeOID(name, lookUp); if (value.indexOf('+') > 0) { X509NameTokenizer vTok = new X509NameTokenizer(value, '+'); this.ordering.addElement(oid); this.values.addElement(vTok.nextToken()); this.added.addElement(Boolean.FALSE); while (vTok.hasMoreTokens()) { String sv = vTok.nextToken(); int ndx = sv.indexOf('='); String nm = sv.substring(0, ndx); String vl = sv.substring(ndx + 1); this.ordering.addElement(decodeOID(nm, lookUp)); this.values.addElement(vl); this.added.addElement(Boolean.TRUE); } } else { this.ordering.addElement(oid); this.values.addElement(value); this.added.addElement(Boolean.FALSE); } } if (reverse) { Vector o = new Vector(); Vector v = new Vector(); Vector a = new Vector(); for (int i = this.ordering.size() - 1; i >= 0; i--) { o.addElement(this.ordering.elementAt(i)); v.addElement(this.values.elementAt(i)); a.addElement(this.added.elementAt(i)); } this.ordering = o; this.values = v; this.added = a; } } /** * return a vector of the oids in the name, in the order they were found. */ public Vector getOIDs() { Vector v = new Vector(); for (int i = 0; i != ordering.size(); i++) { v.addElement(ordering.elementAt(i)); } return v; } /** * return a vector of the values found in the name, in the order they * were found. */ public Vector getValues() { Vector v = new Vector(); for (int i = 0; i != values.size(); i++) { v.addElement(values.elementAt(i)); } return v; } public DERObject toASN1Object() { if (seq == null) { ASN1EncodableVector vec = new ASN1EncodableVector(); ASN1EncodableVector sVec = new ASN1EncodableVector(); DERObjectIdentifier lstOid = null; for (int i = 0; i != ordering.size(); i++) { ASN1EncodableVector v = new ASN1EncodableVector(); DERObjectIdentifier oid = (DERObjectIdentifier)ordering.elementAt(i); v.add(oid); String str = (String)values.elementAt(i); v.add(converter.getConvertedValue(oid, str)); if (lstOid == null || ((Boolean)this.added.elementAt(i)).booleanValue()) { sVec.add(new DERSequence(v)); } else { vec.add(new DERSet(sVec)); sVec = new ASN1EncodableVector(); sVec.add(new DERSequence(v)); } lstOid = oid; } vec.add(new DERSet(sVec)); seq = new DERSequence(vec); } return seq; } /** * @param inOrder if true the order of both X509 names must be the same, * as well as the values associated with each element. */ public boolean equals(Object _obj, boolean inOrder) { if (_obj == this) { return true; } if (!inOrder) { return this.equals(_obj); } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } for(int i = 0; i < _orderingSize; i++) { String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(i)).getId(); String _oVal = (String)_oxn.values.elementAt(i); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { continue; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (!v1.toString().equals(v2.toString())) { return false; } } } else { return false; } } return true; } /** * test for equality - note: case is ignored. */ public boolean equals(Object _obj) { if (_obj == this) { return true; } if (!(_obj instanceof X509Name || _obj instanceof ASN1Sequence)) { return false; } DERObject derO = ((DEREncodable)_obj).getDERObject(); if (this.getDERObject().equals(derO)) { return true; } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } boolean[] _indexes = new boolean[_orderingSize]; for(int i = 0; i < _orderingSize; i++) { boolean _found = false; String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); for(int j = 0; j < _orderingSize; j++) { if (_indexes[j]) { continue; } String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(j)).getId(); String _oVal = (String)_oxn.values.elementAt(j); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { _indexes[j] = true; _found = true; break; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (v1.toString().equals(v2.toString())) { _indexes[j] = true; _found = true; break; } } } } if(!_found) { return false; } } return true; } public int hashCode() { ASN1Sequence seq = (ASN1Sequence)this.getDERObject(); Enumeration e = seq.getObjects(); int hashCode = 0; while (e.hasMoreElements()) { hashCode ^= e.nextElement().hashCode(); } return hashCode; } private void appendValue( StringBuffer buf, Hashtable oidSymbols, DERObjectIdentifier oid, String value) { String sym = (String)oidSymbols.get(oid); if (sym != null) { buf.append(sym); } else { buf.append(oid.getId()); } buf.append('='); int index = buf.length(); buf.append(value); int end = buf.length(); while (index != end) { if ((buf.charAt(index) == ',') || (buf.charAt(index) == '"') || (buf.charAt(index) == '\\') || (buf.charAt(index) == '+') || (buf.charAt(index) == '<') || (buf.charAt(index) == '>') || (buf.charAt(index) == ';')) { buf.insert(index, "\\"); index++; end++; } index++; } } /** * convert the structure to a string - if reverse is true the * oids and values are listed out starting with the last element * in the sequence (ala RFC 2253), otherwise the string will begin * with the first element of the structure. If no string definition * for the oid is found in oidSymbols the string value of the oid is * added. Two standard symbol tables are provided DefaultSymbols, and * RFC2253Symbols as part of this class. * * @param reverse if true start at the end of the sequence and work back. * @param oidSymbols look up table strings for oids. */ public String toString( boolean reverse, Hashtable oidSymbols) { StringBuffer buf = new StringBuffer(); boolean first = true; if (reverse) { for (int i = ordering.size() - 1; i >= 0; i--) { if (first) { first = false; } else { if (((Boolean)added.elementAt(i + 1)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } else { for (int i = 0; i < ordering.size(); i++) { if (first) { first = false; } else { if (((Boolean)added.elementAt(i)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } return buf.toString(); } private String bytesToString( byte[] data) { char[] cs = new char[data.length]; for (int i = 0; i != cs.length; i++) { cs[i] = (char)(data[i] & 0xff); } return new String(cs); } public String toString() { return toString(DefaultReverse, DefaultSymbols); } }
src/org/bouncycastle/asn1/x509/X509Name.java
package org.bouncycastle.asn1.x509; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.Strings; /** * <pre> * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName * * RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue * * AttributeTypeAndValue ::= SEQUENCE { * type OBJECT IDENTIFIER, * value ANY } * </pre> */ public class X509Name extends ASN1Encodable { /** * country code - StringType(SIZE(2)) */ public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6"); /** * organization - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10"); /** * organizational unit name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11"); /** * Title */ public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12"); /** * common name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5"); /** * street - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier STREET = new DERObjectIdentifier("2.5.4.9"); /** * device serial number name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier SERIALNUMBER = SN; /** * locality name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7"); /** * state, or province name - StringType(SIZE(1..64)) */ public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8"); /** * Naming attributes of type X520name */ public static final DERObjectIdentifier SURNAME = new DERObjectIdentifier("2.5.4.4"); public static final DERObjectIdentifier GIVENNAME = new DERObjectIdentifier("2.5.4.42"); public static final DERObjectIdentifier INITIALS = new DERObjectIdentifier("2.5.4.43"); public static final DERObjectIdentifier GENERATION = new DERObjectIdentifier("2.5.4.44"); public static final DERObjectIdentifier UNIQUE_IDENTIFIER = new DERObjectIdentifier("2.5.4.45"); /** * businessCategory - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier BUSINESS_CATEGORY = new DERObjectIdentifier( "2.5.4.15"); /** * postalCode - DirectoryString(SIZE(1..40) */ public static final DERObjectIdentifier POSTAL_CODE = new DERObjectIdentifier( "2.5.4.17"); /** * dnQualifier - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier DN_QUALIFIER = new DERObjectIdentifier( "2.5.4.46"); /** * RFC 3039 Pseudonym - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier PSEUDONYM = new DERObjectIdentifier( "2.5.4.65"); /** * RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z */ public static final DERObjectIdentifier DATE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.1"); /** * RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128) */ public static final DERObjectIdentifier PLACE_OF_BIRTH = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.2"); /** * RFC 3039 Gender - PrintableString (SIZE(1)) -- "M", "F", "m" or "f" */ public static final DERObjectIdentifier GENDER = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.3"); /** * RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_CITIZENSHIP = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.4"); /** * RFC 3039 CountryOfResidence - PrintableString (SIZE (2)) -- ISO 3166 * codes only */ public static final DERObjectIdentifier COUNTRY_OF_RESIDENCE = new DERObjectIdentifier( "1.3.6.1.5.5.7.9.5"); /** * ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64) */ public static final DERObjectIdentifier NAME_AT_BIRTH = new DERObjectIdentifier("1.3.36.8.3.14"); /** * RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF * DirectoryString(SIZE(1..30)) */ public static final DERObjectIdentifier POSTAL_ADDRESS = new DERObjectIdentifier( "2.5.4.16"); /** * Email address (RSA PKCS#9 extension) - IA5String. * <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here. */ public static final DERObjectIdentifier EmailAddress = PKCSObjectIdentifiers.pkcs_9_at_emailAddress; /** * more from PKCS#9 */ public static final DERObjectIdentifier UnstructuredName = PKCSObjectIdentifiers.pkcs_9_at_unstructuredName; public static final DERObjectIdentifier UnstructuredAddress = PKCSObjectIdentifiers.pkcs_9_at_unstructuredAddress; /** * email address in Verisign certificates */ public static final DERObjectIdentifier E = EmailAddress; /* * others... */ public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25"); /** * LDAP User id. */ public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1"); /** * look up table translating OID values into their common symbols - this static is scheduled for deletion */ public static Hashtable OIDLookUp = new Hashtable(); /** * determines whether or not strings should be processed and printed * from back to front. */ public static boolean DefaultReverse = false; /** * default look up table translating OID values into their common symbols following * the convention in RFC 2253 with a few extras */ public static Hashtable DefaultSymbols = OIDLookUp; /** * look up table translating OID values into their common symbols following the convention in RFC 2253 * */ public static Hashtable RFC2253Symbols = new Hashtable(); /** * look up table translating OID values into their common symbols following the convention in RFC 1779 * */ public static Hashtable RFC1779Symbols = new Hashtable(); /** * look up table translating string values into their OIDS - * this static is scheduled for deletion */ public static Hashtable SymbolLookUp = new Hashtable(); /** * look up table translating common symbols into their OIDS. */ public static Hashtable DefaultLookUp = SymbolLookUp; static { DefaultSymbols.put(C, "C"); DefaultSymbols.put(O, "O"); DefaultSymbols.put(T, "T"); DefaultSymbols.put(OU, "OU"); DefaultSymbols.put(CN, "CN"); DefaultSymbols.put(L, "L"); DefaultSymbols.put(ST, "ST"); DefaultSymbols.put(SN, "SN"); DefaultSymbols.put(EmailAddress, "E"); DefaultSymbols.put(DC, "DC"); DefaultSymbols.put(UID, "UID"); DefaultSymbols.put(STREET, "STREET"); DefaultSymbols.put(SURNAME, "SURNAME"); DefaultSymbols.put(GIVENNAME, "GIVENNAME"); DefaultSymbols.put(INITIALS, "INITIALS"); DefaultSymbols.put(GENERATION, "GENERATION"); DefaultSymbols.put(UnstructuredAddress, "unstructuredAddress"); DefaultSymbols.put(UnstructuredName, "unstructuredName"); DefaultSymbols.put(UNIQUE_IDENTIFIER, "UniqueIdentifier"); DefaultSymbols.put(DN_QUALIFIER, "DN"); DefaultSymbols.put(PSEUDONYM, "Pseudonym"); DefaultSymbols.put(POSTAL_ADDRESS, "PostalAddress"); DefaultSymbols.put(NAME_AT_BIRTH, "NameAtBirth"); DefaultSymbols.put(COUNTRY_OF_CITIZENSHIP, "CountryOfCitizenship"); DefaultSymbols.put(COUNTRY_OF_RESIDENCE, "CountryOfResidence"); DefaultSymbols.put(GENDER, "Gender"); DefaultSymbols.put(PLACE_OF_BIRTH, "PlaceOfBirth"); DefaultSymbols.put(DATE_OF_BIRTH, "DateOfBirth"); DefaultSymbols.put(POSTAL_CODE, "PostalCode"); DefaultSymbols.put(BUSINESS_CATEGORY, "BusinessCategory"); RFC2253Symbols.put(C, "C"); RFC2253Symbols.put(O, "O"); RFC2253Symbols.put(OU, "OU"); RFC2253Symbols.put(CN, "CN"); RFC2253Symbols.put(L, "L"); RFC2253Symbols.put(ST, "ST"); RFC2253Symbols.put(STREET, "STREET"); RFC2253Symbols.put(DC, "DC"); RFC2253Symbols.put(UID, "UID"); RFC1779Symbols.put(C, "C"); RFC1779Symbols.put(O, "O"); RFC1779Symbols.put(OU, "OU"); RFC1779Symbols.put(CN, "CN"); RFC1779Symbols.put(L, "L"); RFC1779Symbols.put(ST, "ST"); RFC1779Symbols.put(STREET, "STREET"); DefaultLookUp.put("c", C); DefaultLookUp.put("o", O); DefaultLookUp.put("t", T); DefaultLookUp.put("ou", OU); DefaultLookUp.put("cn", CN); DefaultLookUp.put("l", L); DefaultLookUp.put("st", ST); DefaultLookUp.put("sn", SN); DefaultLookUp.put("serialnumber", SN); DefaultLookUp.put("street", STREET); DefaultLookUp.put("emailaddress", E); DefaultLookUp.put("dc", DC); DefaultLookUp.put("e", E); DefaultLookUp.put("uid", UID); DefaultLookUp.put("surname", SURNAME); DefaultLookUp.put("givenname", GIVENNAME); DefaultLookUp.put("initials", INITIALS); DefaultLookUp.put("generation", GENERATION); DefaultLookUp.put("unstructuredaddress", UnstructuredAddress); DefaultLookUp.put("unstructuredname", UnstructuredName); DefaultLookUp.put("uniqueidentifier", UNIQUE_IDENTIFIER); DefaultLookUp.put("dn", DN_QUALIFIER); DefaultLookUp.put("pseudonym", PSEUDONYM); DefaultLookUp.put("postaladdress", POSTAL_ADDRESS); DefaultLookUp.put("nameofbirth", NAME_AT_BIRTH); DefaultLookUp.put("countryofcitizenship", COUNTRY_OF_CITIZENSHIP); DefaultLookUp.put("countryofresidence", COUNTRY_OF_RESIDENCE); DefaultLookUp.put("gender", GENDER); DefaultLookUp.put("placeofbirth", PLACE_OF_BIRTH); DefaultLookUp.put("dateofbirth", DATE_OF_BIRTH); DefaultLookUp.put("postalcode", POSTAL_CODE); DefaultLookUp.put("businesscategory", BUSINESS_CATEGORY); } private X509NameEntryConverter converter = null; private Vector ordering = new Vector(); private Vector values = new Vector(); private Vector added = new Vector(); private ASN1Sequence seq; /** * Return a X509Name based on the passed in tagged object. * * @param obj tag object holding name. * @param explicit true if explicitly tagged false otherwise. * @return the X509Name */ public static X509Name getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(ASN1Sequence.getInstance(obj, explicit)); } public static X509Name getInstance( Object obj) { if (obj == null || obj instanceof X509Name) { return (X509Name)obj; } else if (obj instanceof ASN1Sequence) { return new X509Name((ASN1Sequence)obj); } throw new IllegalArgumentException("unknown object in factory \"" + obj.getClass().getName()+"\""); } /** * Constructor from ASN1Sequence * * the principal will be a list of constructed sets, each containing an (OID, String) pair. */ public X509Name( ASN1Sequence seq) { this.seq = seq; Enumeration e = seq.getObjects(); while (e.hasMoreElements()) { ASN1Set set = (ASN1Set)e.nextElement(); for (int i = 0; i < set.size(); i++) { ASN1Sequence s = (ASN1Sequence)set.getObjectAt(i); ordering.addElement(s.getObjectAt(0)); DEREncodable value = s.getObjectAt(1); if (value instanceof DERString) { values.addElement(((DERString)value).getString()); } else { values.addElement("#" + bytesToString(Hex.encode(value.getDERObject().getDEREncoded()))); } added.addElement((i != 0) ? new Boolean(true) : new Boolean(false)); } } } /** * constructor from a table of attributes. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. * <p> * <b>Note:</b> if the name you are trying to generate should be * following a specific ordering, you should use the constructor * with the ordering specified below. */ public X509Name( Hashtable attributes) { this(null, attributes); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. */ public X509Name( Vector ordering, Hashtable attributes) { this(ordering, attributes, new X509DefaultEntryConverter()); } /** * Constructor from a table of attributes with ordering. * <p> * it's is assumed the table contains OID/String pairs, and the contents * of the table are copied into an internal table as part of the * construction process. The ordering vector should contain the OIDs * in the order they are meant to be encoded or printed in toString. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector ordering, Hashtable attributes, X509DefaultEntryConverter converter) { this.converter = converter; if (ordering != null) { for (int i = 0; i != ordering.size(); i++) { this.ordering.addElement(ordering.elementAt(i)); this.added.addElement(new Boolean(false)); } } else { Enumeration e = attributes.keys(); while (e.hasMoreElements()) { this.ordering.addElement(e.nextElement()); this.added.addElement(new Boolean(false)); } } for (int i = 0; i != this.ordering.size(); i++) { DERObjectIdentifier oid = (DERObjectIdentifier)this.ordering.elementAt(i); if (attributes.get(oid) == null) { throw new IllegalArgumentException("No attribute for object id - " + oid.getId() + " - passed to distinguished name"); } this.values.addElement(attributes.get(oid)); // copy the hash table } } /** * Takes two vectors one of the oids and the other of the values. */ public X509Name( Vector oids, Vector values) { this(oids, values, new X509DefaultEntryConverter()); } /** * Takes two vectors one of the oids and the other of the values. * <p> * The passed in converter will be used to convert the strings into their * ASN.1 counterparts. */ public X509Name( Vector oids, Vector values, X509NameEntryConverter converter) { this.converter = converter; if (oids.size() != values.size()) { throw new IllegalArgumentException("oids vector must be same length as values."); } for (int i = 0; i < oids.size(); i++) { this.ordering.addElement(oids.elementAt(i)); this.values.addElement(values.elementAt(i)); this.added.addElement(new Boolean(false)); } } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. */ public X509Name( String dirName) { this(DefaultReverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. */ public X509Name( String dirName, X509NameEntryConverter converter) { this(DefaultReverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. If reverse * is true, create the encoded version of the sequence starting from the * last element in the string. */ public X509Name( boolean reverse, String dirName) { this(reverse, DefaultLookUp, dirName); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes with each * string value being converted to its associated ASN.1 type using the passed * in converter. If reverse is true the ASN.1 sequence representing the DN will * be built by starting at the end of the string, rather than the start. */ public X509Name( boolean reverse, String dirName, X509NameEntryConverter converter) { this(reverse, DefaultLookUp, dirName, converter); } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. * <br> * If reverse is true, create the encoded version of the sequence * starting from the last element in the string. * @param reverse true if we should start scanning from the end (RFC 2553). * @param lookUp table of names and their oids. * @param dirName the X.500 string to be parsed. */ public X509Name( boolean reverse, Hashtable lookUp, String dirName) { this(reverse, lookUp, dirName, new X509DefaultEntryConverter()); } private DERObjectIdentifier decodeOID( String name, Hashtable lookUp) { if (Strings.toUpperCase(name).startsWith("OID.")) { return new DERObjectIdentifier(name.substring(4)); } else if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { return new DERObjectIdentifier(name); } DERObjectIdentifier oid = (DERObjectIdentifier)lookUp.get(Strings.toLowerCase(name)); if (oid == null) { throw new IllegalArgumentException("Unknown object id - " + name + " - passed to distinguished name"); } return oid; } /** * Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or * some such, converting it into an ordered set of name attributes. lookUp * should provide a table of lookups, indexed by lowercase only strings and * yielding a DERObjectIdentifier, other than that OID. and numeric oids * will be processed automatically. The passed in converter is used to convert the * string values to the right of each equals sign to their ASN.1 counterparts. * <br> * @param reverse true if we should start scanning from the end, false otherwise. * @param lookUp table of names and oids. * @param dirName the string dirName * @param converter the converter to convert string values into their ASN.1 equivalents */ public X509Name( boolean reverse, Hashtable lookUp, String dirName, X509NameEntryConverter converter) { this.converter = converter; X509NameTokenizer nTok = new X509NameTokenizer(dirName); while (nTok.hasMoreTokens()) { String token = nTok.nextToken(); int index = token.indexOf('='); if (index == -1) { throw new IllegalArgumentException("badly formated directory string"); } String name = token.substring(0, index); String value = token.substring(index + 1); DERObjectIdentifier oid = decodeOID(name, lookUp); if (value.indexOf('+') > 0) { X509NameTokenizer vTok = new X509NameTokenizer(value, '+'); this.ordering.addElement(oid); this.values.addElement(vTok.nextToken()); this.added.addElement(new Boolean(false)); while (vTok.hasMoreTokens()) { String sv = vTok.nextToken(); int ndx = sv.indexOf('='); String nm = sv.substring(0, ndx); String vl = sv.substring(ndx + 1); this.ordering.addElement(decodeOID(nm, lookUp)); this.values.addElement(vl); this.added.addElement(new Boolean(true)); } } else { this.ordering.addElement(oid); this.values.addElement(value); this.added.addElement(new Boolean(false)); } } if (reverse) { Vector o = new Vector(); Vector v = new Vector(); Vector a = new Vector(); for (int i = this.ordering.size() - 1; i >= 0; i--) { o.addElement(this.ordering.elementAt(i)); v.addElement(this.values.elementAt(i)); a.addElement(this.added.elementAt(i)); } this.ordering = o; this.values = v; this.added = a; } } /** * return a vector of the oids in the name, in the order they were found. */ public Vector getOIDs() { Vector v = new Vector(); for (int i = 0; i != ordering.size(); i++) { v.addElement(ordering.elementAt(i)); } return v; } /** * return a vector of the values found in the name, in the order they * were found. */ public Vector getValues() { Vector v = new Vector(); for (int i = 0; i != values.size(); i++) { v.addElement(values.elementAt(i)); } return v; } public DERObject toASN1Object() { if (seq == null) { ASN1EncodableVector vec = new ASN1EncodableVector(); ASN1EncodableVector sVec = new ASN1EncodableVector(); DERObjectIdentifier lstOid = null; for (int i = 0; i != ordering.size(); i++) { ASN1EncodableVector v = new ASN1EncodableVector(); DERObjectIdentifier oid = (DERObjectIdentifier)ordering.elementAt(i); v.add(oid); String str = (String)values.elementAt(i); v.add(converter.getConvertedValue(oid, str)); if (lstOid == null || ((Boolean)this.added.elementAt(i)).booleanValue()) { sVec.add(new DERSequence(v)); } else { vec.add(new DERSet(sVec)); sVec = new ASN1EncodableVector(); sVec.add(new DERSequence(v)); } lstOid = oid; } vec.add(new DERSet(sVec)); seq = new DERSequence(vec); } return seq; } /** * @param inOrder if true the order of both X509 names must be the same, * as well as the values associated with each element. */ public boolean equals(Object _obj, boolean inOrder) { if (_obj == this) { return true; } if (!inOrder) { return this.equals(_obj); } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } for(int i = 0; i < _orderingSize; i++) { String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(i)).getId(); String _oVal = (String)_oxn.values.elementAt(i); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { continue; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (!v1.toString().equals(v2.toString())) { return false; } } } else { return false; } } return true; } /** * test for equality - note: case is ignored. */ public boolean equals(Object _obj) { if (_obj == this) { return true; } if (!(_obj instanceof X509Name || _obj instanceof ASN1Sequence)) { return false; } DERObject derO = ((DEREncodable)_obj).getDERObject(); if (this.getDERObject().equals(derO)) { return true; } if (!(_obj instanceof X509Name)) { return false; } X509Name _oxn = (X509Name)_obj; int _orderingSize = ordering.size(); if (_orderingSize != _oxn.ordering.size()) { return false; } boolean[] _indexes = new boolean[_orderingSize]; for(int i = 0; i < _orderingSize; i++) { boolean _found = false; String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId(); String _val = (String)values.elementAt(i); for(int j = 0; j < _orderingSize; j++) { if (_indexes[j]) { continue; } String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(j)).getId(); String _oVal = (String)_oxn.values.elementAt(j); if (_oid.equals(_oOID)) { _val = Strings.toLowerCase(_val.trim()); _oVal = Strings.toLowerCase(_oVal.trim()); if (_val.equals(_oVal)) { _indexes[j] = true; _found = true; break; } else { StringBuffer v1 = new StringBuffer(); StringBuffer v2 = new StringBuffer(); if (_val.length() != 0) { char c1 = _val.charAt(0); v1.append(c1); for (int k = 1; k < _val.length(); k++) { char c2 = _val.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v1.append(c2); } c1 = c2; } } if (_oVal.length() != 0) { char c1 = _oVal.charAt(0); v2.append(c1); for (int k = 1; k < _oVal.length(); k++) { char c2 = _oVal.charAt(k); if (!(c1 == ' ' && c2 == ' ')) { v2.append(c2); } c1 = c2; } } if (v1.toString().equals(v2.toString())) { _indexes[j] = true; _found = true; break; } } } } if(!_found) { return false; } } return true; } public int hashCode() { ASN1Sequence seq = (ASN1Sequence)this.getDERObject(); Enumeration e = seq.getObjects(); int hashCode = 0; while (e.hasMoreElements()) { hashCode ^= e.nextElement().hashCode(); } return hashCode; } private void appendValue( StringBuffer buf, Hashtable oidSymbols, DERObjectIdentifier oid, String value) { String sym = (String)oidSymbols.get(oid); if (sym != null) { buf.append(sym); } else { buf.append(oid.getId()); } buf.append('='); int index = buf.length(); buf.append(value); int end = buf.length(); while (index != end) { if ((buf.charAt(index) == ',') || (buf.charAt(index) == '"') || (buf.charAt(index) == '\\') || (buf.charAt(index) == '+') || (buf.charAt(index) == '<') || (buf.charAt(index) == '>') || (buf.charAt(index) == ';')) { buf.insert(index, "\\"); index++; end++; } index++; } } /** * convert the structure to a string - if reverse is true the * oids and values are listed out starting with the last element * in the sequence (ala RFC 2253), otherwise the string will begin * with the first element of the structure. If no string definition * for the oid is found in oidSymbols the string value of the oid is * added. Two standard symbol tables are provided DefaultSymbols, and * RFC2253Symbols as part of this class. * * @param reverse if true start at the end of the sequence and work back. * @param oidSymbols look up table strings for oids. */ public String toString( boolean reverse, Hashtable oidSymbols) { StringBuffer buf = new StringBuffer(); boolean first = true; if (reverse) { for (int i = ordering.size() - 1; i >= 0; i--) { if (first) { first = false; } else { if (((Boolean)added.elementAt(i + 1)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } else { for (int i = 0; i < ordering.size(); i++) { if (first) { first = false; } else { if (((Boolean)added.elementAt(i)).booleanValue()) { buf.append('+'); } else { buf.append(','); } } appendValue(buf, oidSymbols, (DERObjectIdentifier)ordering.elementAt(i), (String)values.elementAt(i)); } } return buf.toString(); } private String bytesToString( byte[] data) { char[] cs = new char[data.length]; for (int i = 0; i != cs.length; i++) { cs[i] = (char)(data[i] & 0xff); } return new String(cs); } public String toString() { return toString(DefaultReverse, DefaultSymbols); } }
Use Boolean class sensibly
src/org/bouncycastle/asn1/x509/X509Name.java
Use Boolean class sensibly
<ide><path>rc/org/bouncycastle/asn1/x509/X509Name.java <ide> { <ide> values.addElement("#" + bytesToString(Hex.encode(value.getDERObject().getDEREncoded()))); <ide> } <del> added.addElement((i != 0) ? new Boolean(true) : new Boolean(false)); <add> added.addElement(Boolean.valueOf(i != 0)); <ide> } <ide> } <ide> } <ide> for (int i = 0; i != ordering.size(); i++) <ide> { <ide> this.ordering.addElement(ordering.elementAt(i)); <del> this.added.addElement(new Boolean(false)); <add> this.added.addElement(Boolean.FALSE); <ide> } <ide> } <ide> else <ide> while (e.hasMoreElements()) <ide> { <ide> this.ordering.addElement(e.nextElement()); <del> this.added.addElement(new Boolean(false)); <add> this.added.addElement(Boolean.FALSE); <ide> } <ide> } <ide> <ide> { <ide> this.ordering.addElement(oids.elementAt(i)); <ide> this.values.addElement(values.elementAt(i)); <del> this.added.addElement(new Boolean(false)); <add> this.added.addElement(Boolean.FALSE); <ide> } <ide> } <ide> <ide> <ide> this.ordering.addElement(oid); <ide> this.values.addElement(vTok.nextToken()); <del> this.added.addElement(new Boolean(false)); <add> this.added.addElement(Boolean.FALSE); <ide> <ide> while (vTok.hasMoreTokens()) <ide> { <ide> String vl = sv.substring(ndx + 1); <ide> this.ordering.addElement(decodeOID(nm, lookUp)); <ide> this.values.addElement(vl); <del> this.added.addElement(new Boolean(true)); <add> this.added.addElement(Boolean.TRUE); <ide> } <ide> } <ide> else <ide> { <ide> this.ordering.addElement(oid); <ide> this.values.addElement(value); <del> this.added.addElement(new Boolean(false)); <add> this.added.addElement(Boolean.FALSE); <ide> } <ide> } <ide>
JavaScript
mit
2ec9c696db47cf9ba4f0c3db6edd0dae8f02cd83
0
laat/nurture,laat/nurture
// @flow /* eslint-disable no-console */ import sane from 'sane'; import chalk from 'chalk'; import ora from 'ora'; import { queue } from 'async'; import execCommand from './utils/exec'; const check = (bool?: boolean) => (bool ? chalk.green('✓') : chalk.red('✗')); const printDefinition = (wd, { change, add, delete: del, command, patterns, }: WatchDefinition) => { let warning = ''; if (change === false && del === false && add === false) { warning = `\n${chalk.yellow('WARNING')}: not listening to any triggers`; return; } console.log(` > Watching ${wd} > Patterns: ${patterns.join(', ')} > Command: '${command}' > Triggers: add ${check(add)} change ${check(change)} delete ${check(del)} ${warning}`); }; async function exec(wd, command, files, appendFiles, config) { if (files.length === 0) { return; } let commandToRun; if (appendFiles) { commandToRun = `${command} ${files.join(' ')}`; } else { commandToRun = command; } console.log(`\n> ${chalk.green('Watch triggered at')}: ${wd}\n> ${commandToRun}`); const options = { shell: true, cwd: wd, env: process.env }; await execCommand(commandToRun, options, config); } export default (watchman: boolean) => { const spinner = ora('Watching for changes'); const startSpinner = () => { spinner.start(); }; const taskQueue = queue((fn, cb) => { fn().then(cb).catch((err) => { console.error('Task failed', err); cb(); }); }, 1); taskQueue.drain = startSpinner; const addDefinition = (wd: string, config: PhaseConfig = {}) => ({ patterns, command, appendFiles = false, add = true, delete: del = false, change = true, }: WatchDefinition) => { const watchDefinition = { patterns, command, appendFiles, add, delete: del, change, }; printDefinition(wd, watchDefinition); const watcher = sane(wd, { glob: patterns, watchman }); const newChanges = new Set(); const newChange = file => { newChanges.add(file); taskQueue.push(async () => { spinner.stop(); const files = Array.from(newChanges); newChanges.clear(); await exec(wd, command, files, appendFiles, config); }); }; if (change) { watcher.on('change', newChange); } if (add) { watcher.on('add', newChange); } if (del) { watcher.on('delete', newChange); } }; return { add: addDefinition, start: startSpinner, }; };
src/watch.js
// @flow /* eslint-disable no-console */ import sane from 'sane'; import chalk from 'chalk'; import ora from 'ora'; import { queue } from 'async'; import execCommand from './utils/exec'; const check = (bool?: boolean) => (bool ? chalk.green('✓') : chalk.red('✗')); const printDefinition = (wd, { change, add, delete: del, command, patterns, }: WatchDefinition) => { let warning = ''; if (change === false && del === false && add === false) { warning = `\n${chalk.yellow('WARNING')}: not listening to any triggers`; return; } console.log(` > Watching ${wd} > Patterns: ${patterns.join(', ')} > Command: '${command}' > Triggers: add ${check(add)} change ${check(change)} delete ${check(del)} ${warning}`); }; async function exec(wd, command, files, appendFiles, config) { if (files.length === 0) { return; } let commandToRun; if (appendFiles) { commandToRun = `${command} ${files.join(' ')}`; } else { commandToRun = command; } console.log(`\n> Watch triggered at: ${wd}\n> ${commandToRun}`); const options = { shell: true, cwd: wd, env: process.env }; await execCommand(commandToRun, options, config); } export default (watchman: boolean) => { const spinner = ora('Watching for changes'); const startSpinner = () => { spinner.start(); }; const taskQueue = queue((fn, cb) => { fn().then(cb).catch((err) => { console.error('Task failed', err); cb(); }); }, 1); taskQueue.drain = startSpinner; const addDefinition = (wd: string, config: PhaseConfig = {}) => ({ patterns, command, appendFiles = false, add = true, delete: del = false, change = true, }: WatchDefinition) => { const watchDefinition = { patterns, command, appendFiles, add, delete: del, change, }; printDefinition(wd, watchDefinition); const watcher = sane(wd, { glob: patterns, watchman }); const newChanges = new Set(); const newChange = file => { newChanges.add(file); taskQueue.push(async () => { spinner.stop(); const files = Array.from(newChanges); newChanges.clear(); await exec(wd, command, files, appendFiles, config); }); }; if (change) { watcher.on('change', newChange); } if (add) { watcher.on('add', newChange); } if (del) { watcher.on('delete', newChange); } }; return { add: addDefinition, start: startSpinner, }; };
easier to identify where a trigger starts
src/watch.js
easier to identify where a trigger starts
<ide><path>rc/watch.js <ide> commandToRun = command; <ide> } <ide> <del> console.log(`\n> Watch triggered at: ${wd}\n> ${commandToRun}`); <add> console.log(`\n> ${chalk.green('Watch triggered at')}: ${wd}\n> ${commandToRun}`); <ide> const options = { shell: true, cwd: wd, env: process.env }; <ide> await execCommand(commandToRun, options, config); <ide> }
Java
bsd-2-clause
463a11da596eb8db981406d6b67801e3f030e2e9
0
runelite/runelite,runelite/runelite,runelite/runelite
/* * Copyright (c) 2018, Adam <[email protected]> * Copyright (c) 2018, Kamiel * Copyright (c) 2019, Rami <https://github.com/Rami-J> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.menuentryswapper; import com.google.common.annotations.VisibleForTesting; import static com.google.common.base.Predicates.alwaysTrue; import static com.google.common.base.Predicates.equalTo; import com.google.common.base.Strings; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.inject.Provides; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.ItemComposition; import net.runelite.api.KeyCode; import net.runelite.api.MenuAction; import net.runelite.api.MenuEntry; import net.runelite.api.NPC; import net.runelite.api.NPCComposition; import net.runelite.api.NpcID; import net.runelite.api.ObjectComposition; import net.runelite.api.ParamID; import net.runelite.api.events.ClientTick; import net.runelite.api.events.MenuOpened; import net.runelite.api.events.PostItemComposition; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.ItemManager; import net.runelite.client.game.ItemVariationMapping; import net.runelite.client.menus.MenuManager; import net.runelite.client.menus.WidgetMenuOption; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.ArdougneCloakMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.DesertAmuletMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.KaramjaGlovesMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.MorytaniaLegsMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.RadasBlessingMode; import net.runelite.client.util.Text; @PluginDescriptor( name = "Menu Entry Swapper", description = "Change the default option that is displayed when hovering over objects", tags = {"npcs", "inventory", "items", "objects"}, enabledByDefault = false ) @Slf4j public class MenuEntrySwapperPlugin extends Plugin { private static final String CONFIGURE = "Configure"; private static final String SAVE = "Save"; private static final String RESET = "Reset"; private static final String LEFT_CLICK_MENU_TARGET = "Left-click"; private static final String SHIFT_CLICK_MENU_TARGET = "Shift-click"; private static final String SHIFTCLICK_CONFIG_GROUP = "shiftclick"; private static final String ITEM_KEY_PREFIX = "item_"; private static final String OBJECT_KEY_PREFIX = "object_"; private static final String NPC_KEY_PREFIX = "npc_"; private static final String NPC_SHIFT_KEY_PREFIX = "npc_shift_"; private static final String WORN_ITEM_KEY_PREFIX = "wornitem_"; private static final String WORN_ITEM_SHIFT_KEY_PREFIX = "wornitem_shift_"; // Shift click private static final WidgetMenuOption FIXED_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption FIXED_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); // Left click private static final WidgetMenuOption FIXED_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption FIXED_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final List<MenuAction> NPC_MENU_TYPES = ImmutableList.of( MenuAction.NPC_FIRST_OPTION, MenuAction.NPC_SECOND_OPTION, MenuAction.NPC_THIRD_OPTION, MenuAction.NPC_FOURTH_OPTION, MenuAction.NPC_FIFTH_OPTION ); private static final List<MenuAction> OBJECT_MENU_TYPES = ImmutableList.of( MenuAction.GAME_OBJECT_FIRST_OPTION, MenuAction.GAME_OBJECT_SECOND_OPTION, MenuAction.GAME_OBJECT_THIRD_OPTION, MenuAction.GAME_OBJECT_FOURTH_OPTION // GAME_OBJECT_FIFTH_OPTION gets sorted underneath Walk here after we swap, so it doesn't work ); private static final Set<String> ESSENCE_MINE_NPCS = ImmutableSet.of( "aubury", "archmage sedridor", "wizard distentor", "wizard cromperty", "brimstail" ); private static final Set<String> TEMPOROSS_NPCS = ImmutableSet.of( "captain dudi", "captain pudi", "first mate deri", "first mate peri" ); @Inject private Client client; @Inject private ClientThread clientThread; @Inject private MenuEntrySwapperConfig config; @Inject private ConfigManager configManager; @Inject private MenuManager menuManager; @Inject private ItemManager itemManager; @Inject private ChatMessageManager chatMessageManager; private boolean configuringShiftClick = false; private boolean configuringLeftClick = false; private final Multimap<String, Swap> swaps = LinkedHashMultimap.create(); private final ArrayListMultimap<String, Integer> optionIndexes = ArrayListMultimap.create(); @Provides MenuEntrySwapperConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(MenuEntrySwapperConfig.class); } @Override public void startUp() { enableCustomization(); setupSwaps(); } @Override public void shutDown() { disableCustomization(); swaps.clear(); } @VisibleForTesting void setupSwaps() { swap("talk-to", "mage of zamorak", "teleport", config::swapAbyssTeleport); swap("talk-to", "rionasta", "send-parcel", config::swapHardWoodGroveParcel); swap("talk-to", "captain khaled", "task", config::swapCaptainKhaled); swap("talk-to", "bank", config::swapBank); swap("talk-to", "contract", config::swapContract); swap("talk-to", "exchange", config::swapExchange); swap("talk-to", "help", config::swapHelp); swap("talk-to", "nets", config::swapNets); swap("talk-to", "repairs", config::swapDarkMage); // make sure assignment swap is higher priority than trade swap for slayer masters swap("talk-to", "assignment", config::swapAssignment); swap("talk-to", "trade", config::swapTrade); swap("talk-to", "trade-with", config::swapTrade); swap("talk-to", "shop", config::swapTrade); swap("talk-to", "robin", "claim-slime", config::claimSlime); swap("talk-to", "travel", config::swapTravel); swap("talk-to", "pay-fare", config::swapTravel); swap("talk-to", "charter", config::swapTravel); swap("talk-to", "take-boat", config::swapTravel); swap("talk-to", "fly", config::swapTravel); swap("talk-to", "jatizso", config::swapTravel); swap("talk-to", "neitiznot", config::swapTravel); swap("talk-to", "rellekka", config::swapTravel); swap("talk-to", "ungael", config::swapTravel); swap("talk-to", "pirate's cove", config::swapTravel); swap("talk-to", "waterbirth island", config::swapTravel); swap("talk-to", "island of stone", config::swapTravel); swap("talk-to", "miscellania", config::swapTravel); swap("talk-to", "follow", config::swapTravel); swap("talk-to", "transport", config::swapTravel); swap("talk-to", "pay", config::swapPay); swapContains("talk-to", alwaysTrue(), "pay (", config::swapPay); swap("talk-to", "decant", config::swapDecant); swap("talk-to", "quick-travel", config::swapQuick); swap("talk-to", "enchant", config::swapEnchant); swap("talk-to", "start-minigame", config::swapStartMinigame); swap("talk-to", ESSENCE_MINE_NPCS::contains, "teleport", config::swapEssenceMineTeleport); swap("talk-to", "collect", config::swapCollectMiscellania); swap("talk-to", "deposit-items", config::swapDepositItems); swap("talk-to", TEMPOROSS_NPCS::contains, "leave", config::swapTemporossLeave); swap("leave tomb", "quick-leave", config::swapQuickLeave); swap("tomb door", "quick-leave", config::swapQuickLeave); swap("pass", "energy barrier", "pay-toll(2-ecto)", config::swapTravel); swap("open", "gate", "pay-toll(10gp)", config::swapTravel); swap("open", "hardwood grove doors", "quick-pay(100)", config::swapHardWoodGrove); swap("inspect", "trapdoor", "travel", config::swapTravel); swap("board", "travel cart", "pay-fare", config::swapTravel); swap("board", "sacrificial boat", "quick-board", config::swapQuick); swap("cage", "harpoon", config::swapHarpoon); swap("big net", "harpoon", config::swapHarpoon); swap("net", "harpoon", config::swapHarpoon); swap("lure", "bait", config::swapBait); swap("net", "bait", config::swapBait); swap("small net", "bait", config::swapBait); swap("enter", "portal", "home", () -> config.swapHomePortal() == HouseMode.HOME); swap("enter", "portal", "build mode", () -> config.swapHomePortal() == HouseMode.BUILD_MODE); swap("enter", "portal", "friend's house", () -> config.swapHomePortal() == HouseMode.FRIENDS_HOUSE); swap("view", "add-house", () -> config.swapHouseAdvertisement() == HouseAdvertisementMode.ADD_HOUSE); swap("view", "visit-last", () -> config.swapHouseAdvertisement() == HouseAdvertisementMode.VISIT_LAST); for (String option : new String[]{"zanaris", "tree"}) { swapContains(option, alwaysTrue(), "last-destination", () -> config.swapFairyRing() == FairyRingMode.LAST_DESTINATION); swapContains(option, alwaysTrue(), "configure", () -> config.swapFairyRing() == FairyRingMode.CONFIGURE); } swapContains("configure", alwaysTrue(), "last-destination", () -> config.swapFairyRing() == FairyRingMode.LAST_DESTINATION || config.swapFairyRing() == FairyRingMode.ZANARIS); swapContains("tree", alwaysTrue(), "zanaris", () -> config.swapFairyRing() == FairyRingMode.ZANARIS); swap("check", "reset", config::swapBoxTrap); swap("dismantle", "reset", config::swapBoxTrap); swap("take", "lay", config::swapBoxTrap); swap("pick-up", "chase", config::swapChase); swap("interact", target -> target.endsWith("birdhouse"), "empty", config::swapBirdhouseEmpty); swap("enter", "the gauntlet", "enter-corrupted", config::swapGauntlet); swap("enter", "quick-enter", config::swapQuick); swap("enter-crypt", "quick-enter", config::swapQuick); swap("ring", "quick-start", config::swapQuick); swap("pass", "quick-pass", config::swapQuick); swap("pass", "quick pass", config::swapQuick); swap("open", "quick-open", config::swapQuick); swap("climb-down", "quick-start", config::swapQuick); swap("climb-down", "pay", config::swapQuick); swap("admire", "teleport", config::swapAdmire); swap("admire", "spellbook", config::swapAdmire); swap("admire", "perks", config::swapAdmire); swap("teleport menu", "duel arena", config::swapJewelleryBox); swap("teleport menu", "castle wars", config::swapJewelleryBox); swap("teleport menu", "ferox enclave", config::swapJewelleryBox); swap("teleport menu", "burthorpe", config::swapJewelleryBox); swap("teleport menu", "barbarian outpost", config::swapJewelleryBox); swap("teleport menu", "corporeal beast", config::swapJewelleryBox); swap("teleport menu", "tears of guthix", config::swapJewelleryBox); swap("teleport menu", "wintertodt camp", config::swapJewelleryBox); swap("teleport menu", "warriors' guild", config::swapJewelleryBox); swap("teleport menu", "champions' guild", config::swapJewelleryBox); swap("teleport menu", "monastery", config::swapJewelleryBox); swap("teleport menu", "ranging guild", config::swapJewelleryBox); swap("teleport menu", "fishing guild", config::swapJewelleryBox); swap("teleport menu", "mining guild", config::swapJewelleryBox); swap("teleport menu", "crafting guild", config::swapJewelleryBox); swap("teleport menu", "cooking guild", config::swapJewelleryBox); swap("teleport menu", "woodcutting guild", config::swapJewelleryBox); swap("teleport menu", "farming guild", config::swapJewelleryBox); swap("teleport menu", "miscellania", config::swapJewelleryBox); swap("teleport menu", "grand exchange", config::swapJewelleryBox); swap("teleport menu", "falador park", config::swapJewelleryBox); swap("teleport menu", "dondakan's rock", config::swapJewelleryBox); swap("teleport menu", "edgeville", config::swapJewelleryBox); swap("teleport menu", "karamja", config::swapJewelleryBox); swap("teleport menu", "draynor village", config::swapJewelleryBox); swap("teleport menu", "al kharid", config::swapJewelleryBox); Arrays.asList( "annakarl", "ape atoll dungeon", "ardougne", "barrows", "battlefront", "camelot", "carrallangar", "catherby", "cemetery", "draynor manor", "falador", "fenkenstrain's castle", "fishing guild", "ghorrock", "grand exchange", "great kourend", "harmony island", "kharyrll", "lumbridge", "arceuus library", "lunar isle", "marim", "mind altar", "salve graveyard", "seers' village", "senntisten", "troll stronghold", "varrock", "watchtower", "waterbirth island", "weiss", "west ardougne", "yanille" ).forEach(location -> swap(location, "portal nexus", "teleport menu", config::swapPortalNexus)); swap("shared", "private", config::swapPrivate); swap("pick", "pick-lots", config::swapPick); swap("view offer", "abort offer", () -> shiftModifier() && config.swapGEAbort()); Arrays.asList( "honest jimmy", "bert the sandman", "advisor ghrim", "dark mage", "lanthus", "spria", "turael", "mazchna", "vannaka", "chaeldar", "nieve", "steve", "duradel", "krystilia", "konar", "murphy", "cyrisus", "smoggy", "ginea", "watson", "barbarian guard", "amy", "random" ).forEach(npc -> swap("cast", "npc contact", npc, () -> shiftModifier() && config.swapNpcContact())); swap("value", "buy 1", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_1); swap("value", "buy 5", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_5); swap("value", "buy 10", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_10); swap("value", "buy 50", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_50); swap("value", "sell 1", () -> shiftModifier() && config.shopSell() == SellMode.SELL_1); swap("value", "sell 5", () -> shiftModifier() && config.shopSell() == SellMode.SELL_5); swap("value", "sell 10", () -> shiftModifier() && config.shopSell() == SellMode.SELL_10); swap("value", "sell 50", () -> shiftModifier() && config.shopSell() == SellMode.SELL_50); swap("wear", "tele to poh", config::swapTeleToPoh); swap("wear", "rub", config::swapTeleportItem); swap("wear", "teleport", config::swapTeleportItem); swap("wield", "teleport", config::swapTeleportItem); swap("wield", "invoke", config::swapTeleportItem); swap("wear", "teleports", config::swapTeleportItem); swap("wear", "farm teleport", () -> config.swapArdougneCloakMode() == ArdougneCloakMode.FARM); swap("wear", "monastery teleport", () -> config.swapArdougneCloakMode() == ArdougneCloakMode.MONASTERY); swap("wear", "gem mine", () -> config.swapKaramjaGlovesMode() == KaramjaGlovesMode.GEM_MINE); swap("wear", "duradel", () -> config.swapKaramjaGlovesMode() == KaramjaGlovesMode.DURADEL); swap("equip", "kourend woodland", () -> config.swapRadasBlessingMode() == RadasBlessingMode.KOUREND_WOODLAND); swap("equip", "mount karuulm", () -> config.swapRadasBlessingMode() == RadasBlessingMode.MOUNT_KARUULM); swap("wear", "ecto teleport", () -> config.swapMorytaniaLegsMode() == MorytaniaLegsMode.ECTOFUNTUS); swap("wear", "burgh teleport", () -> config.swapMorytaniaLegsMode() == MorytaniaLegsMode.BURGH_DE_ROTT); swap("wear", "nardah", () -> config.swapDesertAmuletMode() == DesertAmuletMode.NARDAH); swap("wear", "kalphite cave", () -> config.swapDesertAmuletMode() == DesertAmuletMode.KALPHITE_CAVE); swap("bury", "use", config::swapBones); swap("wield", "battlestaff", "use", config::swapBattlestaves); swap("clean", "use", config::swapHerbs); swap("read", "recite-prayer", config::swapPrayerBook); swap("collect-note", "collect-item", () -> config.swapGEItemCollect() == GEItemCollectMode.ITEMS); swap("collect-notes", "collect-items", () -> config.swapGEItemCollect() == GEItemCollectMode.ITEMS); swap("collect-item", "collect-note", () -> config.swapGEItemCollect() == GEItemCollectMode.NOTES); swap("collect-items", "collect-notes", () -> config.swapGEItemCollect() == GEItemCollectMode.NOTES); swap("collect to inventory", "collect to bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-note", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-notes", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-item", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-items", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("tan 1", "tan all", config::swapTan); swapTeleport("varrock teleport", "grand exchange"); swapTeleport("camelot teleport", "seers'"); swapTeleport("watchtower teleport", "yanille"); swapHouseTeleport("cast", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.CAST); swapHouseTeleport("outside", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.OUTSIDE); swapHouseTeleport("group: choose", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.GROUP_CHOOSE); swapHouseTeleport("group: previous", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.GROUP_PREVIOUS); swap("eat", "guzzle", config::swapRockCake); swap("travel", "dive", config::swapRowboatDive); swap("climb", "climb-up", () -> (shiftModifier() ? config.swapStairsShiftClick() : config.swapStairsLeftClick()) == MenuEntrySwapperConfig.StairsMode.CLIMB_UP); swap("climb", "climb-down", () -> (shiftModifier() ? config.swapStairsShiftClick() : config.swapStairsLeftClick()) == MenuEntrySwapperConfig.StairsMode.CLIMB_DOWN); } private void swap(String option, String swappedOption, Supplier<Boolean> enabled) { swap(option, alwaysTrue(), swappedOption, enabled); } private void swap(String option, String target, String swappedOption, Supplier<Boolean> enabled) { swap(option, equalTo(target), swappedOption, enabled); } private void swap(String option, Predicate<String> targetPredicate, String swappedOption, Supplier<Boolean> enabled) { swaps.put(option, new Swap(alwaysTrue(), targetPredicate, swappedOption, enabled, true)); } private void swapContains(String option, Predicate<String> targetPredicate, String swappedOption, Supplier<Boolean> enabled) { swaps.put(option, new Swap(alwaysTrue(), targetPredicate, swappedOption, enabled, false)); } private void swapTeleport(String option, String swappedOption) { swap("cast", option, swappedOption, () -> shiftModifier() && config.swapTeleportSpell()); swap(swappedOption, option, "cast", () -> shiftModifier() && config.swapTeleportSpell()); } private void swapHouseTeleport(String swappedOption, Supplier<Boolean> enabled) { swap("cast", "teleport to house", swappedOption, enabled); swap("outside", "teleport to house", swappedOption, enabled); } @Subscribe public void onConfigChanged(ConfigChanged event) { if (event.getGroup().equals(MenuEntrySwapperConfig.GROUP) && (event.getKey().equals("shiftClickCustomization") || event.getKey().equals("leftClickCustomization"))) { enableCustomization(); } else if (event.getGroup().equals(SHIFTCLICK_CONFIG_GROUP) && event.getKey().startsWith(ITEM_KEY_PREFIX)) { clientThread.invoke(this::resetItemCompositionCache); } } private void resetItemCompositionCache() { client.getItemCompositionCache().reset(); } private Integer getItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); String config = configManager.getConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setItemSwapConfig(boolean shift, int itemId, int index) { itemId = ItemVariationMapping.map(itemId); configManager.setConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId, index); } private void unsetItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); configManager.unsetConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId); } private Integer getWornItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setWornItemSwapConfig(boolean shift, int itemId, int index) { itemId = ItemVariationMapping.map(itemId); configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId, index); } private void unsetWornItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId); } private void enableCustomization() { rebuildCustomizationMenus(); // set shift click action index on the item compositions clientThread.invoke(this::resetItemCompositionCache); } private void disableCustomization() { removeCusomizationMenus(); configuringShiftClick = configuringLeftClick = false; // flush item compositions to reset the shift click action index clientThread.invoke(this::resetItemCompositionCache); } @Subscribe public void onMenuOpened(MenuOpened event) { if (!configuringShiftClick && !configuringLeftClick) { configureObjectClick(event); configureNpcClick(event); configureWornItems(event); return; } final MenuEntry firstEntry = event.getFirstEntry(); if (firstEntry == null) { return; } final int itemId; if (firstEntry.getType() == MenuAction.WIDGET_TARGET && firstEntry.getWidget().getId() == WidgetInfo.INVENTORY.getId()) { itemId = firstEntry.getWidget().getItemId(); } else if (firstEntry.isItemOp()) { itemId = firstEntry.getItemId(); } else { return; } int activeOp = 0; final ItemComposition itemComposition = itemManager.getItemComposition(itemId); if (configuringShiftClick) { // For shift-click read the active action off of the item composition, since it may be set by // that even if we have no existing config for it final int shiftClickActionIndex = itemComposition.getShiftClickActionIndex(); if (shiftClickActionIndex >= 0) { activeOp = 1 + shiftClickActionIndex; } else { // Otherwise it is possible that we have Use swap configured Integer config = getItemSwapConfig(true, itemId); if (config != null && config == -1) { activeOp = -1; } } } else { // Apply left click action from configuration Integer config = getItemSwapConfig(false, itemId); if (config != null) { activeOp = config >= 0 ? 1 + config : -1; } } MenuEntry[] entries = event.getMenuEntries(); for (MenuEntry entry : entries) { if (entry.getType() == MenuAction.WIDGET_TARGET && entry.getWidget().getId() == WidgetInfo.INVENTORY.getId() && entry.getWidget().getItemId() == itemId) { entry.setType(MenuAction.RUNELITE); entry.onClick(e -> { log.debug("Set {} item swap for {} to USE", configuringShiftClick ? "shift" : "left", itemId); setItemSwapConfig(configuringShiftClick, itemId, -1); }); if (activeOp == -1) { entry.setOption("* " + entry.getOption()); } } else if (entry.isItemOp() && entry.getItemId() == itemId) { final int itemOp = entry.getItemOp(); entry.setType(MenuAction.RUNELITE); entry.onClick(e -> { log.debug("Set {} item swap config for {} to {}", configuringShiftClick ? "shift" : "left", itemId, itemOp - 1); setItemSwapConfig(configuringShiftClick, itemId, itemOp - 1); }); if (itemOp == activeOp) { entry.setOption("* " + entry.getOption()); } } } client.createMenuEntry(-1) .setOption(RESET) .setTarget(configuringShiftClick ? SHIFT_CLICK_MENU_TARGET : LEFT_CLICK_MENU_TARGET) .setType(MenuAction.RUNELITE) .onClick(e -> unsetItemSwapConfig(configuringShiftClick, itemId)); } private void configureObjectClick(MenuOpened event) { if (!shiftModifier() || !config.objectLeftClickCustomization()) { return; } MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { MenuEntry entry = entries[idx]; if (entry.getType() == MenuAction.EXAMINE_OBJECT) { final ObjectComposition composition = client.getObjectDefinition(entry.getIdentifier()); final String[] actions = composition.getActions(); final Integer swapConfig = getObjectSwapConfig(composition.getId()); final MenuAction currentAction = swapConfig != null ? OBJECT_MENU_TYPES.get(swapConfig) : defaultAction(composition); for (int actionIdx = 0; actionIdx < OBJECT_MENU_TYPES.size(); ++actionIdx) { if (Strings.isNullOrEmpty(actions[actionIdx])) { continue; } final int menuIdx = actionIdx; final MenuAction menuAction = OBJECT_MENU_TYPES.get(actionIdx); if (currentAction == menuAction) { continue; } client.createMenuEntry(idx) .setOption("Swap " + actions[actionIdx]) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to '").append(actions[menuIdx]).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set object swap for {} to {}", composition.getId(), menuAction); final MenuAction defaultAction = defaultAction(composition); if (defaultAction != menuAction) { setObjectSwapConfig(composition.getId(), menuIdx); } else { unsetObjectSwapConfig(composition.getId()); } }); } } } } private Consumer<MenuEntry> walkHereConsumer(boolean shift, NPCComposition composition) { return e -> { final String message = new ChatMessageBuilder() .append("The default ").append(shift ? "shift" : "left").append(" click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to Walk here.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set npc {} click swap for {} to Walk here", shift ? "shift" : "left", composition.getId()); setNpcSwapConfig(shift, composition.getId(), -1); }; } private void configureNpcClick(MenuOpened event) { if (!shiftModifier() || !config.npcLeftClickCustomization()) { return; } MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { final MenuEntry entry = entries[idx]; final MenuAction type = entry.getType(); if (type == MenuAction.EXAMINE_NPC) { final NPC npc = entry.getNpc(); assert npc != null; final NPCComposition composition = npc.getTransformedComposition(); assert composition != null; final String[] actions = composition.getActions(); final Integer swapConfig = getNpcSwapConfig(false, composition.getId()); final boolean hasAttack = Arrays.stream(composition.getActions()).anyMatch("Attack"::equalsIgnoreCase); final MenuAction currentAction = swapConfig == null ? // Attackable NPCs always have Attack as the first, last (deprioritized), or when hidden, no, option. // Due to this the default action would be either Attack or the first non-Attack option, based on // the game settings. Since it may be valid to swap an option up to override Attack, even when Attack // is left-click, we cannot assume any default currentAction on attackable NPCs. // Non-attackable NPCS have a predictable default action which we can prevent a swap to if no swap // config is set, which just avoids showing a Swap option on a 1-op NPC, which looks odd. (hasAttack ? null : defaultAction(composition)) : (swapConfig == -1 ? MenuAction.WALK : NPC_MENU_TYPES.get(swapConfig)); for (int actionIdx = 0; actionIdx < NPC_MENU_TYPES.size(); ++actionIdx) { // Attack can be swapped with the in-game settings, and this becomes very confusing if we try // to swap Attack and the game also tries to swap it (by deprioritizing), so just use the in-game // setting. if (Strings.isNullOrEmpty(actions[actionIdx]) || "Attack".equalsIgnoreCase(actions[actionIdx])) { continue; } final int menuIdx = actionIdx; final MenuAction menuAction = NPC_MENU_TYPES.get(actionIdx); if (currentAction == menuAction) { continue; } if ("Knock-Out".equals(actions[actionIdx]) || "Lure".equals(actions[actionIdx])) { // https://secure.runescape.com/m=news/another-message-about-unofficial-clients?oldschool=1 continue; } client.createMenuEntry(idx) .setOption("Swap " + actions[actionIdx]) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to '").append(actions[menuIdx]).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set npc swap for {} to {}", composition.getId(), menuAction); setNpcSwapConfig(false, composition.getId(), menuIdx); }); } // Walk here swap client.createMenuEntry(idx) .setOption("Swap left click Walk here") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(walkHereConsumer(false, composition)); client.createMenuEntry(idx) .setOption("Swap shift click Walk here") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(walkHereConsumer(true, composition)); if (getNpcSwapConfig(true, composition.getId()) != null || getNpcSwapConfig(false, composition.getId()) != null) // NOPMD: BrokenNullCheck { // Reset client.createMenuEntry(idx) .setOption("Reset swap") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left and shift click options for '").append(Text.removeTags(composition.getName())).append("' ") .append("have been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset npc swap for {}", composition.getId()); unsetNpcSwapConfig(true, composition.getId()); unsetNpcSwapConfig(false, composition.getId()); }); } } } } private void configureWornItems(MenuOpened event) { if (!shiftModifier()) { return; } final MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { final MenuEntry entry = entries[idx]; Widget w = entry.getWidget(); if (w != null && WidgetInfo.TO_GROUP(w.getId()) == WidgetID.EQUIPMENT_GROUP_ID && "Examine".equals(entry.getOption()) && entry.getIdentifier() == 10) { w = w.getChild(1); if (w != null && w.getItemId() > -1) { final ItemComposition itemComposition = itemManager.getItemComposition(w.getItemId()); final Integer leftClickOp = getWornItemSwapConfig(false, itemComposition.getId()); final Integer shiftClickOp = getWornItemSwapConfig(true, itemComposition.getId()); for (int paramId = ParamID.OC_ITEM_OP1, opId = 2; paramId <= ParamID.OC_ITEM_OP8; ++paramId, ++opId) { final String opName = itemComposition.getStringValue(paramId); if (!Strings.isNullOrEmpty(opName)) { if (leftClickOp == null || leftClickOp != opId) { client.createMenuEntry(idx) .setOption("Swap left click " + opName) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(wornItemConsumer(itemComposition, opName, opId, false)); } if (shiftClickOp == null || shiftClickOp != opId) { client.createMenuEntry(idx) .setOption("Swap shift click " + opName) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(wornItemConsumer(itemComposition, opName, opId, true)); } } } if (leftClickOp != null) { client.createMenuEntry(idx) .setOption("Reset swap left click") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default worn left click option for '").append(itemComposition.getName()).append("' ") .append("has been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset worn item left swap for {}", itemComposition.getName()); unsetWornItemSwapConfig(false, itemComposition.getId()); }); } if (shiftClickOp != null) { client.createMenuEntry(idx) .setOption("Reset swap shift click") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default worn shift click option for '").append(itemComposition.getName()).append("' ") .append("has been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset worn item shift swap for {}", itemComposition.getName()); unsetWornItemSwapConfig(true, itemComposition.getId()); }); } } } } } private Consumer<MenuEntry> wornItemConsumer(ItemComposition itemComposition, String opName, int opIdx, boolean shift) { return e -> { final String message = new ChatMessageBuilder() .append("The default worn ").append(shift ? "shift" : "left").append(" click option for '").append(Text.removeTags(itemComposition.getName())).append("' ") .append("has been set to '").append(opName).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set worn item {} swap for {} to {}", shift ? "shift" : "left", itemComposition.getName(), opIdx); setWornItemSwapConfig(shift, itemComposition.getId(), opIdx); }; } private boolean swapBank(MenuEntry menuEntry, MenuAction type) { if (type != MenuAction.CC_OP && type != MenuAction.CC_OP_LOW_PRIORITY) { return false; } final int widgetGroupId = WidgetInfo.TO_GROUP(menuEntry.getParam1()); final boolean isDepositBoxPlayerInventory = widgetGroupId == WidgetID.DEPOSIT_BOX_GROUP_ID; final boolean isChambersOfXericStorageUnitPlayerInventory = widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_INVENTORY_GROUP_ID; final boolean isGroupStoragePlayerInventory = widgetGroupId == WidgetID.GROUP_STORAGE_INVENTORY_GROUP_ID; // Swap to shift-click deposit behavior // Deposit- op 1 is the current withdraw amount 1/5/10/x for deposit box interface and chambers of xeric storage unit. // Deposit- op 2 is the current withdraw amount 1/5/10/x for bank interface if (shiftModifier() && config.bankDepositShiftClick() != ShiftDepositMode.OFF && type == MenuAction.CC_OP && menuEntry.getIdentifier() == (isDepositBoxPlayerInventory || isGroupStoragePlayerInventory || isChambersOfXericStorageUnitPlayerInventory ? 1 : 2) && (menuEntry.getOption().startsWith("Deposit-") || menuEntry.getOption().startsWith("Store") || menuEntry.getOption().startsWith("Donate"))) { ShiftDepositMode shiftDepositMode = config.bankDepositShiftClick(); final int opId = isDepositBoxPlayerInventory ? shiftDepositMode.getIdentifierDepositBox() : isChambersOfXericStorageUnitPlayerInventory ? shiftDepositMode.getIdentifierChambersStorageUnit() : isGroupStoragePlayerInventory ? shiftDepositMode.getIdentifierGroupStorage() : shiftDepositMode.getIdentifier(); final MenuAction action = opId >= 6 ? MenuAction.CC_OP_LOW_PRIORITY : MenuAction.CC_OP; bankModeSwap(action, opId); return true; } // Swap to shift-click withdraw behavior // Deposit- op 1 is the current withdraw amount 1/5/10/x if (shiftModifier() && config.bankWithdrawShiftClick() != ShiftWithdrawMode.OFF && type == MenuAction.CC_OP && menuEntry.getIdentifier() == 1 && menuEntry.getOption().startsWith("Withdraw")) { ShiftWithdrawMode shiftWithdrawMode = config.bankWithdrawShiftClick(); final MenuAction action; final int opId; if (widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_PRIVATE_GROUP_ID || widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_SHARED_GROUP_ID) { action = MenuAction.CC_OP; opId = shiftWithdrawMode.getIdentifierChambersStorageUnit(); } else { action = shiftWithdrawMode.getMenuAction(); opId = shiftWithdrawMode.getIdentifier(); } bankModeSwap(action, opId); return true; } return false; } private void bankModeSwap(MenuAction entryType, int entryIdentifier) { MenuEntry[] menuEntries = client.getMenuEntries(); for (int i = menuEntries.length - 1; i >= 0; --i) { MenuEntry entry = menuEntries[i]; if (entry.getType() == entryType && entry.getIdentifier() == entryIdentifier) { // Raise the priority of the op so it doesn't get sorted later entry.setType(MenuAction.CC_OP); menuEntries[i] = menuEntries[menuEntries.length - 1]; menuEntries[menuEntries.length - 1] = entry; client.setMenuEntries(menuEntries); break; } } } private void swapMenuEntry(MenuEntry[] menuEntries, int index, MenuEntry menuEntry) { final int eventId = menuEntry.getIdentifier(); final MenuAction menuAction = menuEntry.getType(); final String option = Text.removeTags(menuEntry.getOption()).toLowerCase(); final String target = Text.removeTags(menuEntry.getTarget()).toLowerCase(); final NPC hintArrowNpc = client.getHintArrowNpc(); // Don't swap on hint arrow npcs, usually they need "Talk-to" for clues. if (hintArrowNpc != null && hintArrowNpc.getIndex() == eventId && NPC_MENU_TYPES.contains(menuAction)) { return; } final boolean itemOp = menuEntry.isItemOp(); // Custom shift-click item swap if (shiftModifier() && itemOp) { // Special case use shift click due to items not actually containing a "Use" option, making // the client unable to perform the swap itself. if (config.shiftClickCustomization() && !option.equals("use")) { Integer customOption = getItemSwapConfig(true, menuEntry.getItemId()); if (customOption != null && customOption == -1) { swap(menuEntries, "use", target, index, true); } } // don't perform swaps on items when shift is held; instead prefer the client menu swap, which // we may have overwrote return; } // Custom left-click item swap if (itemOp) { Integer swapIndex = getItemSwapConfig(false, menuEntry.getItemId()); if (swapIndex != null) { final int swapAction = swapIndex >= 0 ? 1 + swapIndex : -1; if (swapAction == -1) { swap(menuEntries, "use", target, index, true); } else if (swapAction == menuEntry.getItemOp()) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); } return; } } // Worn items swap Widget w = menuEntry.getWidget(); if (w != null && WidgetInfo.TO_GROUP(w.getId()) == WidgetID.EQUIPMENT_GROUP_ID) { w = w.getChild(1); if (w != null && w.getItemId() > -1) { final Integer wornItemSwapConfig = getWornItemSwapConfig(shiftModifier(), w.getItemId()); if (wornItemSwapConfig != null) { if (wornItemSwapConfig == menuEntry.getIdentifier()) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); } return; } } } if (OBJECT_MENU_TYPES.contains(menuAction)) { // Get multiloc id int objectId = eventId; ObjectComposition objectComposition = client.getObjectDefinition(objectId); if (objectComposition.getImpostorIds() != null) { objectComposition = objectComposition.getImpostor(); objectId = objectComposition.getId(); } Integer customOption = getObjectSwapConfig(objectId); if (customOption != null) { MenuAction swapAction = OBJECT_MENU_TYPES.get(customOption); if (swapAction == menuAction) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); return; } } } if (NPC_MENU_TYPES.contains(menuAction)) { final NPC npc = menuEntry.getNpc(); assert npc != null; final NPCComposition composition = npc.getTransformedComposition(); Integer customOption = getNpcSwapConfig(shiftModifier(), composition.getId()); if (customOption != null) { // Walk here swap if (customOption == -1) { // we can achieve this by just deprioritizing the normal npc menus menuEntry.setDeprioritized(true); } else { MenuAction swapAction = NPC_MENU_TYPES.get(customOption); if (swapAction == menuAction) { // Advance to the top-most op for this NPC. Normally menuEntries.length - 1 is examine, and swapping // with that works due to it being sorted later, but if other plugins like NPC indicators add additional // menus before examine that are also >1000, like RUNELITE menus, that would result in the >1000 menus being // reordered relative to each other. int i = index; while (i < menuEntries.length - 1 && NPC_MENU_TYPES.contains(menuEntries[i + 1].getType())) { ++i; } swap(optionIndexes, menuEntries, index, i); return; } } } } if (swapBank(menuEntry, menuAction)) { return; } // Built-in swaps Collection<Swap> swaps = this.swaps.get(option); for (Swap swap : swaps) { if (swap.getTargetPredicate().test(target) && swap.getEnabled().get()) { if (swap(menuEntries, swap.getSwappedOption(), target, index, swap.isStrict())) { break; } } } } @Subscribe public void onClientTick(ClientTick clientTick) { // The menu is not rebuilt when it is open, so don't swap or else it will // repeatedly swap entries if (client.getGameState() != GameState.LOGGED_IN || client.isMenuOpen()) { return; } MenuEntry[] menuEntries = client.getMenuEntries(); // Build option map for quick lookup in findIndex int idx = 0; optionIndexes.clear(); for (MenuEntry entry : menuEntries) { String option = Text.removeTags(entry.getOption()).toLowerCase(); optionIndexes.put(option, idx++); } // Perform swaps idx = 0; for (MenuEntry entry : menuEntries) { swapMenuEntry(menuEntries, idx++, entry); } if (config.removeDeadNpcMenus()) { removeDeadNpcs(); } } private void removeDeadNpcs() { MenuEntry[] oldEntries = client.getMenuEntries(); MenuEntry[] newEntries = Arrays.stream(oldEntries) .filter(e -> { final NPC npc = e.getNpc(); if (npc == null) { return true; } final int id = npc.getId(); switch (id) { // These NPCs hit 0hp but don't actually die case NpcID.GARGOYLE: case NpcID.GARGOYLE_413: case NpcID.GARGOYLE_1543: case NpcID.ZYGOMITE: case NpcID.ZYGOMITE_1024: case NpcID.ANCIENT_ZYGOMITE: case NpcID.ROCKSLUG: case NpcID.ROCKSLUG_422: case NpcID.DESERT_LIZARD: case NpcID.DESERT_LIZARD_460: case NpcID.DESERT_LIZARD_461: case NpcID.ICE_DEMON: case NpcID.ICE_DEMON_7585: return true; default: return !npc.isDead(); } }) .toArray(MenuEntry[]::new); if (oldEntries.length != newEntries.length) { client.setMenuEntries(newEntries); } } @Subscribe public void onPostItemComposition(PostItemComposition event) { if (!config.shiftClickCustomization()) { // since shift-click is done by the client we have to check if our shift click customization is on // prior to altering the item shift click action index. return; } ItemComposition itemComposition = event.getItemComposition(); Integer option = getItemSwapConfig(true, itemComposition.getId()); if (option != null && option < itemComposition.getInventoryActions().length) { itemComposition.setShiftClickActionIndex(option); } } private boolean swap(MenuEntry[] menuEntries, String option, String target, int index, boolean strict) { // find option to swap with int optionIdx = findIndex(menuEntries, index, option, target, strict); if (optionIdx >= 0) { swap(optionIndexes, menuEntries, optionIdx, index); return true; } return false; } private int findIndex(MenuEntry[] entries, int limit, String option, String target, boolean strict) { if (strict) { List<Integer> indexes = optionIndexes.get(option); // We want the last index which matches the target, as that is what is top-most // on the menu for (int i = indexes.size() - 1; i >= 0; --i) { int idx = indexes.get(i); MenuEntry entry = entries[idx]; String entryTarget = Text.removeTags(entry.getTarget()).toLowerCase(); // Limit to the last index which is prior to the current entry if (idx < limit && entryTarget.equals(target)) { return idx; } } } else { // Without strict matching we have to iterate all entries up to the current limit... for (int i = limit - 1; i >= 0; i--) { MenuEntry entry = entries[i]; String entryOption = Text.removeTags(entry.getOption()).toLowerCase(); String entryTarget = Text.removeTags(entry.getTarget()).toLowerCase(); if (entryOption.contains(option.toLowerCase()) && entryTarget.equals(target)) { return i; } } } return -1; } private void swap(ArrayListMultimap<String, Integer> optionIndexes, MenuEntry[] entries, int index1, int index2) { if (index1 == index2) { return; } MenuEntry entry1 = entries[index1], entry2 = entries[index2]; entries[index1] = entry2; entries[index2] = entry1; // Item op4 and op5 are CC_OP_LOW_PRIORITY so they get added underneath Use, // but this also causes them to get sorted after client tick. Change them to // CC_OP to avoid this. if (entry1.isItemOp() && entry1.getType() == MenuAction.CC_OP_LOW_PRIORITY) { entry1.setType(MenuAction.CC_OP); } if (entry2.isItemOp() && entry2.getType() == MenuAction.CC_OP_LOW_PRIORITY) { entry2.setType(MenuAction.CC_OP); } client.setMenuEntries(entries); // Update optionIndexes String option1 = Text.removeTags(entry1.getOption()).toLowerCase(), option2 = Text.removeTags(entry2.getOption()).toLowerCase(); List<Integer> list1 = optionIndexes.get(option1), list2 = optionIndexes.get(option2); // call remove(Object) instead of remove(int) list1.remove((Integer) index1); list2.remove((Integer) index2); sortedInsert(list1, index2); sortedInsert(list2, index1); } private static <T extends Comparable<? super T>> void sortedInsert(List<T> list, T value) // NOPMD: UnusedPrivateMethod: false positive { int idx = Collections.binarySearch(list, value); list.add(idx < 0 ? -idx - 1 : idx, value); } private void removeCusomizationMenus() { // Shift click menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_SC); // Left click menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_LC); } private void rebuildCustomizationMenus() { removeCusomizationMenus(); if (configuringLeftClick) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_LC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_LC, this::save); } else if (configuringShiftClick) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_SC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_SC, this::save); } else { // Left click if (config.leftClickCustomization()) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_LC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_LC, this::configure); } // Shift click if (config.shiftClickCustomization()) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_SC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_SC, this::configure); } } } private boolean shiftModifier() { return client.isKeyPressed(KeyCode.KC_SHIFT); } private void save(MenuEntry menuEntry) { configuringLeftClick = configuringShiftClick = false; rebuildCustomizationMenus(); } private void configure(MenuEntry menuEntry) { String target = Text.removeTags(menuEntry.getTarget()); configuringShiftClick = target.equals(SHIFT_CLICK_MENU_TARGET); configuringLeftClick = target.equals(LEFT_CLICK_MENU_TARGET); rebuildCustomizationMenus(); } private Integer getObjectSwapConfig(int objectId) { String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setObjectSwapConfig(int objectId, int index) { configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId, index); } private void unsetObjectSwapConfig(int objectId) { configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId); } private static MenuAction defaultAction(ObjectComposition objectComposition) { String[] actions = objectComposition.getActions(); for (int i = 0; i < OBJECT_MENU_TYPES.size(); ++i) { if (!Strings.isNullOrEmpty(actions[i])) { return OBJECT_MENU_TYPES.get(i); } } return null; } private Integer getNpcSwapConfig(boolean shift, int npcId) { String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setNpcSwapConfig(boolean shift, int npcId, int index) { configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId, index); } private void unsetNpcSwapConfig(boolean shift, int npcId) { configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId); } private static MenuAction defaultAction(NPCComposition composition) { String[] actions = composition.getActions(); for (int i = 0; i < NPC_MENU_TYPES.size(); ++i) { if (!Strings.isNullOrEmpty(actions[i]) && !actions[i].equalsIgnoreCase("Attack")) { return NPC_MENU_TYPES.get(i); } } return null; } }
runelite-client/src/main/java/net/runelite/client/plugins/menuentryswapper/MenuEntrySwapperPlugin.java
/* * Copyright (c) 2018, Adam <[email protected]> * Copyright (c) 2018, Kamiel * Copyright (c) 2019, Rami <https://github.com/Rami-J> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.menuentryswapper; import com.google.common.annotations.VisibleForTesting; import static com.google.common.base.Predicates.alwaysTrue; import static com.google.common.base.Predicates.equalTo; import com.google.common.base.Strings; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; import com.google.inject.Provides; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.ItemComposition; import net.runelite.api.KeyCode; import net.runelite.api.MenuAction; import net.runelite.api.MenuEntry; import net.runelite.api.NPC; import net.runelite.api.NPCComposition; import net.runelite.api.NpcID; import net.runelite.api.ObjectComposition; import net.runelite.api.ParamID; import net.runelite.api.events.ClientTick; import net.runelite.api.events.MenuOpened; import net.runelite.api.events.PostItemComposition; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.callback.ClientThread; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.ItemManager; import net.runelite.client.game.ItemVariationMapping; import net.runelite.client.menus.MenuManager; import net.runelite.client.menus.WidgetMenuOption; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.ArdougneCloakMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.DesertAmuletMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.KaramjaGlovesMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.MorytaniaLegsMode; import static net.runelite.client.plugins.menuentryswapper.MenuEntrySwapperConfig.RadasBlessingMode; import net.runelite.client.util.Text; @PluginDescriptor( name = "Menu Entry Swapper", description = "Change the default option that is displayed when hovering over objects", tags = {"npcs", "inventory", "items", "objects"}, enabledByDefault = false ) @Slf4j public class MenuEntrySwapperPlugin extends Plugin { private static final String CONFIGURE = "Configure"; private static final String SAVE = "Save"; private static final String RESET = "Reset"; private static final String LEFT_CLICK_MENU_TARGET = "Left-click"; private static final String SHIFT_CLICK_MENU_TARGET = "Shift-click"; private static final String SHIFTCLICK_CONFIG_GROUP = "shiftclick"; private static final String ITEM_KEY_PREFIX = "item_"; private static final String OBJECT_KEY_PREFIX = "object_"; private static final String NPC_KEY_PREFIX = "npc_"; private static final String NPC_SHIFT_KEY_PREFIX = "npc_shift_"; private static final String WORN_ITEM_KEY_PREFIX = "wornitem_"; private static final String WORN_ITEM_SHIFT_KEY_PREFIX = "wornitem_shift_"; // Shift click private static final WidgetMenuOption FIXED_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption FIXED_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC = new WidgetMenuOption(CONFIGURE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC = new WidgetMenuOption(SAVE, SHIFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); // Left click private static final WidgetMenuOption FIXED_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption FIXED_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.FIXED_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC = new WidgetMenuOption(CONFIGURE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final WidgetMenuOption RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC = new WidgetMenuOption(SAVE, LEFT_CLICK_MENU_TARGET, WidgetInfo.RESIZABLE_VIEWPORT_BOTTOM_LINE_INVENTORY_TAB); private static final List<MenuAction> NPC_MENU_TYPES = ImmutableList.of( MenuAction.NPC_FIRST_OPTION, MenuAction.NPC_SECOND_OPTION, MenuAction.NPC_THIRD_OPTION, MenuAction.NPC_FOURTH_OPTION, MenuAction.NPC_FIFTH_OPTION ); private static final List<MenuAction> OBJECT_MENU_TYPES = ImmutableList.of( MenuAction.GAME_OBJECT_FIRST_OPTION, MenuAction.GAME_OBJECT_SECOND_OPTION, MenuAction.GAME_OBJECT_THIRD_OPTION, MenuAction.GAME_OBJECT_FOURTH_OPTION // GAME_OBJECT_FIFTH_OPTION gets sorted underneath Walk here after we swap, so it doesn't work ); private static final Set<String> ESSENCE_MINE_NPCS = ImmutableSet.of( "aubury", "archmage sedridor", "wizard distentor", "wizard cromperty", "brimstail" ); private static final Set<String> TEMPOROSS_NPCS = ImmutableSet.of( "captain dudi", "captain pudi", "first mate deri", "first mate peri" ); @Inject private Client client; @Inject private ClientThread clientThread; @Inject private MenuEntrySwapperConfig config; @Inject private ConfigManager configManager; @Inject private MenuManager menuManager; @Inject private ItemManager itemManager; @Inject private ChatMessageManager chatMessageManager; private boolean configuringShiftClick = false; private boolean configuringLeftClick = false; private final Multimap<String, Swap> swaps = LinkedHashMultimap.create(); private final ArrayListMultimap<String, Integer> optionIndexes = ArrayListMultimap.create(); @Provides MenuEntrySwapperConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(MenuEntrySwapperConfig.class); } @Override public void startUp() { enableCustomization(); setupSwaps(); } @Override public void shutDown() { disableCustomization(); swaps.clear(); } @VisibleForTesting void setupSwaps() { swap("talk-to", "mage of zamorak", "teleport", config::swapAbyssTeleport); swap("talk-to", "rionasta", "send-parcel", config::swapHardWoodGroveParcel); swap("talk-to", "captain khaled", "task", config::swapCaptainKhaled); swap("talk-to", "bank", config::swapBank); swap("talk-to", "contract", config::swapContract); swap("talk-to", "exchange", config::swapExchange); swap("talk-to", "help", config::swapHelp); swap("talk-to", "nets", config::swapNets); swap("talk-to", "repairs", config::swapDarkMage); // make sure assignment swap is higher priority than trade swap for slayer masters swap("talk-to", "assignment", config::swapAssignment); swap("talk-to", "trade", config::swapTrade); swap("talk-to", "trade-with", config::swapTrade); swap("talk-to", "shop", config::swapTrade); swap("talk-to", "robin", "claim-slime", config::claimSlime); swap("talk-to", "travel", config::swapTravel); swap("talk-to", "pay-fare", config::swapTravel); swap("talk-to", "charter", config::swapTravel); swap("talk-to", "take-boat", config::swapTravel); swap("talk-to", "fly", config::swapTravel); swap("talk-to", "jatizso", config::swapTravel); swap("talk-to", "neitiznot", config::swapTravel); swap("talk-to", "rellekka", config::swapTravel); swap("talk-to", "ungael", config::swapTravel); swap("talk-to", "pirate's cove", config::swapTravel); swap("talk-to", "waterbirth island", config::swapTravel); swap("talk-to", "island of stone", config::swapTravel); swap("talk-to", "miscellania", config::swapTravel); swap("talk-to", "follow", config::swapTravel); swap("talk-to", "transport", config::swapTravel); swap("talk-to", "pay", config::swapPay); swapContains("talk-to", alwaysTrue(), "pay (", config::swapPay); swap("talk-to", "decant", config::swapDecant); swap("talk-to", "quick-travel", config::swapQuick); swap("talk-to", "enchant", config::swapEnchant); swap("talk-to", "start-minigame", config::swapStartMinigame); swap("talk-to", ESSENCE_MINE_NPCS::contains, "teleport", config::swapEssenceMineTeleport); swap("talk-to", "collect", config::swapCollectMiscellania); swap("talk-to", "deposit-items", config::swapDepositItems); swap("talk-to", TEMPOROSS_NPCS::contains, "leave", config::swapTemporossLeave); swap("leave tomb", "quick-leave", config::swapQuickLeave); swap("tomb door", "quick-leave", config::swapQuickLeave); swap("pass", "energy barrier", "pay-toll(2-ecto)", config::swapTravel); swap("open", "gate", "pay-toll(10gp)", config::swapTravel); swap("open", "hardwood grove doors", "quick-pay(100)", config::swapHardWoodGrove); swap("inspect", "trapdoor", "travel", config::swapTravel); swap("board", "travel cart", "pay-fare", config::swapTravel); swap("board", "sacrificial boat", "quick-board", config::swapQuick); swap("cage", "harpoon", config::swapHarpoon); swap("big net", "harpoon", config::swapHarpoon); swap("net", "harpoon", config::swapHarpoon); swap("lure", "bait", config::swapBait); swap("net", "bait", config::swapBait); swap("small net", "bait", config::swapBait); swap("enter", "portal", "home", () -> config.swapHomePortal() == HouseMode.HOME); swap("enter", "portal", "build mode", () -> config.swapHomePortal() == HouseMode.BUILD_MODE); swap("enter", "portal", "friend's house", () -> config.swapHomePortal() == HouseMode.FRIENDS_HOUSE); swap("view", "add-house", () -> config.swapHouseAdvertisement() == HouseAdvertisementMode.ADD_HOUSE); swap("view", "visit-last", () -> config.swapHouseAdvertisement() == HouseAdvertisementMode.VISIT_LAST); for (String option : new String[]{"zanaris", "tree"}) { swapContains(option, alwaysTrue(), "last-destination", () -> config.swapFairyRing() == FairyRingMode.LAST_DESTINATION); swapContains(option, alwaysTrue(), "configure", () -> config.swapFairyRing() == FairyRingMode.CONFIGURE); } swapContains("configure", alwaysTrue(), "last-destination", () -> config.swapFairyRing() == FairyRingMode.LAST_DESTINATION || config.swapFairyRing() == FairyRingMode.ZANARIS); swapContains("tree", alwaysTrue(), "zanaris", () -> config.swapFairyRing() == FairyRingMode.ZANARIS); swap("check", "reset", config::swapBoxTrap); swap("dismantle", "reset", config::swapBoxTrap); swap("take", "lay", config::swapBoxTrap); swap("pick-up", "chase", config::swapChase); swap("interact", target -> target.endsWith("birdhouse"), "empty", config::swapBirdhouseEmpty); swap("enter", "the gauntlet", "enter-corrupted", config::swapGauntlet); swap("enter", "quick-enter", config::swapQuick); swap("enter-crypt", "quick-enter", config::swapQuick); swap("ring", "quick-start", config::swapQuick); swap("pass", "quick-pass", config::swapQuick); swap("pass", "quick pass", config::swapQuick); swap("open", "quick-open", config::swapQuick); swap("climb-down", "quick-start", config::swapQuick); swap("climb-down", "pay", config::swapQuick); swap("admire", "teleport", config::swapAdmire); swap("admire", "spellbook", config::swapAdmire); swap("admire", "perks", config::swapAdmire); swap("teleport menu", "duel arena", config::swapJewelleryBox); swap("teleport menu", "castle wars", config::swapJewelleryBox); swap("teleport menu", "ferox enclave", config::swapJewelleryBox); swap("teleport menu", "burthorpe", config::swapJewelleryBox); swap("teleport menu", "barbarian outpost", config::swapJewelleryBox); swap("teleport menu", "corporeal beast", config::swapJewelleryBox); swap("teleport menu", "tears of guthix", config::swapJewelleryBox); swap("teleport menu", "wintertodt camp", config::swapJewelleryBox); swap("teleport menu", "warriors' guild", config::swapJewelleryBox); swap("teleport menu", "champions' guild", config::swapJewelleryBox); swap("teleport menu", "monastery", config::swapJewelleryBox); swap("teleport menu", "ranging guild", config::swapJewelleryBox); swap("teleport menu", "fishing guild", config::swapJewelleryBox); swap("teleport menu", "mining guild", config::swapJewelleryBox); swap("teleport menu", "crafting guild", config::swapJewelleryBox); swap("teleport menu", "cooking guild", config::swapJewelleryBox); swap("teleport menu", "woodcutting guild", config::swapJewelleryBox); swap("teleport menu", "farming guild", config::swapJewelleryBox); swap("teleport menu", "miscellania", config::swapJewelleryBox); swap("teleport menu", "grand exchange", config::swapJewelleryBox); swap("teleport menu", "falador park", config::swapJewelleryBox); swap("teleport menu", "dondakan's rock", config::swapJewelleryBox); swap("teleport menu", "edgeville", config::swapJewelleryBox); swap("teleport menu", "karamja", config::swapJewelleryBox); swap("teleport menu", "draynor village", config::swapJewelleryBox); swap("teleport menu", "al kharid", config::swapJewelleryBox); Arrays.asList( "annakarl", "ape atoll dungeon", "ardougne", "barrows", "battlefront", "camelot", "carrallangar", "catherby", "cemetery", "draynor manor", "falador", "fenkenstrain's castle", "fishing guild", "ghorrock", "grand exchange", "great kourend", "harmony island", "kharyrll", "lumbridge", "arceuus library", "lunar isle", "marim", "mind altar", "salve graveyard", "seers' village", "senntisten", "troll stronghold", "varrock", "watchtower", "waterbirth island", "weiss", "west ardougne", "yanille" ).forEach(location -> swap(location, "portal nexus", "teleport menu", config::swapPortalNexus)); swap("shared", "private", config::swapPrivate); swap("pick", "pick-lots", config::swapPick); swap("view offer", "abort offer", () -> shiftModifier() && config.swapGEAbort()); Arrays.asList( "honest jimmy", "bert the sandman", "advisor ghrim", "dark mage", "lanthus", "spria", "turael", "mazchna", "vannaka", "chaeldar", "nieve", "steve", "duradel", "krystilia", "konar", "murphy", "cyrisus", "smoggy", "ginea", "watson", "barbarian guard", "amy", "random" ).forEach(npc -> swap("cast", "npc contact", npc, () -> shiftModifier() && config.swapNpcContact())); swap("value", "buy 1", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_1); swap("value", "buy 5", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_5); swap("value", "buy 10", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_10); swap("value", "buy 50", () -> shiftModifier() && config.shopBuy() == BuyMode.BUY_50); swap("value", "sell 1", () -> shiftModifier() && config.shopSell() == SellMode.SELL_1); swap("value", "sell 5", () -> shiftModifier() && config.shopSell() == SellMode.SELL_5); swap("value", "sell 10", () -> shiftModifier() && config.shopSell() == SellMode.SELL_10); swap("value", "sell 50", () -> shiftModifier() && config.shopSell() == SellMode.SELL_50); swap("wear", "tele to poh", config::swapTeleToPoh); swap("wear", "rub", config::swapTeleportItem); swap("wear", "teleport", config::swapTeleportItem); swap("wield", "teleport", config::swapTeleportItem); swap("wield", "invoke", config::swapTeleportItem); swap("wear", "teleports", config::swapTeleportItem); swap("wear", "farm teleport", () -> config.swapArdougneCloakMode() == ArdougneCloakMode.FARM); swap("wear", "monastery teleport", () -> config.swapArdougneCloakMode() == ArdougneCloakMode.MONASTERY); swap("wear", "gem mine", () -> config.swapKaramjaGlovesMode() == KaramjaGlovesMode.GEM_MINE); swap("wear", "duradel", () -> config.swapKaramjaGlovesMode() == KaramjaGlovesMode.DURADEL); swap("equip", "kourend woodland", () -> config.swapRadasBlessingMode() == RadasBlessingMode.KOUREND_WOODLAND); swap("equip", "mount karuulm", () -> config.swapRadasBlessingMode() == RadasBlessingMode.MOUNT_KARUULM); swap("wear", "ecto teleport", () -> config.swapMorytaniaLegsMode() == MorytaniaLegsMode.ECTOFUNTUS); swap("wear", "burgh teleport", () -> config.swapMorytaniaLegsMode() == MorytaniaLegsMode.BURGH_DE_ROTT); swap("wear", "nardah", () -> config.swapDesertAmuletMode() == DesertAmuletMode.NARDAH); swap("wear", "kalphite cave", () -> config.swapDesertAmuletMode() == DesertAmuletMode.KALPHITE_CAVE); swap("bury", "use", config::swapBones); swap("wield", "battlestaff", "use", config::swapBattlestaves); swap("clean", "use", config::swapHerbs); swap("read", "recite-prayer", config::swapPrayerBook); swap("collect-note", "collect-item", () -> config.swapGEItemCollect() == GEItemCollectMode.ITEMS); swap("collect-notes", "collect-items", () -> config.swapGEItemCollect() == GEItemCollectMode.ITEMS); swap("collect-item", "collect-note", () -> config.swapGEItemCollect() == GEItemCollectMode.NOTES); swap("collect-items", "collect-notes", () -> config.swapGEItemCollect() == GEItemCollectMode.NOTES); swap("collect to inventory", "collect to bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-note", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-notes", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-item", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("collect-items", "bank", () -> config.swapGEItemCollect() == GEItemCollectMode.BANK); swap("tan 1", "tan all", config::swapTan); swapTeleport("varrock teleport", "grand exchange"); swapTeleport("camelot teleport", "seers'"); swapTeleport("watchtower teleport", "yanille"); swapHouseTeleport("cast", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.CAST); swapHouseTeleport("outside", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.OUTSIDE); swapHouseTeleport("group: choose", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.GROUP_CHOOSE); swapHouseTeleport("group: previous", () -> shiftModifier() && config.swapHouseTeleportSpell() == MenuEntrySwapperConfig.HouseTeleportMode.GROUP_PREVIOUS); swap("eat", "guzzle", config::swapRockCake); swap("travel", "dive", config::swapRowboatDive); swap("climb", "climb-up", () -> (shiftModifier() ? config.swapStairsShiftClick() : config.swapStairsLeftClick()) == MenuEntrySwapperConfig.StairsMode.CLIMB_UP); swap("climb", "climb-down", () -> (shiftModifier() ? config.swapStairsShiftClick() : config.swapStairsLeftClick()) == MenuEntrySwapperConfig.StairsMode.CLIMB_DOWN); } private void swap(String option, String swappedOption, Supplier<Boolean> enabled) { swap(option, alwaysTrue(), swappedOption, enabled); } private void swap(String option, String target, String swappedOption, Supplier<Boolean> enabled) { swap(option, equalTo(target), swappedOption, enabled); } private void swap(String option, Predicate<String> targetPredicate, String swappedOption, Supplier<Boolean> enabled) { swaps.put(option, new Swap(alwaysTrue(), targetPredicate, swappedOption, enabled, true)); } private void swapContains(String option, Predicate<String> targetPredicate, String swappedOption, Supplier<Boolean> enabled) { swaps.put(option, new Swap(alwaysTrue(), targetPredicate, swappedOption, enabled, false)); } private void swapTeleport(String option, String swappedOption) { swap("cast", option, swappedOption, () -> shiftModifier() && config.swapTeleportSpell()); swap(swappedOption, option, "cast", () -> shiftModifier() && config.swapTeleportSpell()); } private void swapHouseTeleport(String swappedOption, Supplier<Boolean> enabled) { swap("cast", "teleport to house", swappedOption, enabled); swap("outside", "teleport to house", swappedOption, enabled); } @Subscribe public void onConfigChanged(ConfigChanged event) { if (event.getGroup().equals(MenuEntrySwapperConfig.GROUP) && (event.getKey().equals("shiftClickCustomization") || event.getKey().equals("leftClickCustomization"))) { enableCustomization(); } else if (event.getGroup().equals(SHIFTCLICK_CONFIG_GROUP) && event.getKey().startsWith(ITEM_KEY_PREFIX)) { clientThread.invoke(this::resetItemCompositionCache); } } private void resetItemCompositionCache() { client.getItemCompositionCache().reset(); } private Integer getItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); String config = configManager.getConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setItemSwapConfig(boolean shift, int itemId, int index) { itemId = ItemVariationMapping.map(itemId); configManager.setConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId, index); } private void unsetItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); configManager.unsetConfiguration(shift ? SHIFTCLICK_CONFIG_GROUP : MenuEntrySwapperConfig.GROUP, ITEM_KEY_PREFIX + itemId); } private Integer getWornItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setWornItemSwapConfig(boolean shift, int itemId, int index) { itemId = ItemVariationMapping.map(itemId); configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId, index); } private void unsetWornItemSwapConfig(boolean shift, int itemId) { itemId = ItemVariationMapping.map(itemId); configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? WORN_ITEM_SHIFT_KEY_PREFIX : WORN_ITEM_KEY_PREFIX) + itemId); } private void enableCustomization() { rebuildCustomizationMenus(); // set shift click action index on the item compositions clientThread.invoke(this::resetItemCompositionCache); } private void disableCustomization() { removeCusomizationMenus(); configuringShiftClick = configuringLeftClick = false; // flush item compositions to reset the shift click action index clientThread.invoke(this::resetItemCompositionCache); } @Subscribe public void onMenuOpened(MenuOpened event) { if (!configuringShiftClick && !configuringLeftClick) { configureObjectClick(event); configureNpcClick(event); configureWornItems(event); return; } final MenuEntry firstEntry = event.getFirstEntry(); if (firstEntry == null) { return; } final int itemId; if (firstEntry.getType() == MenuAction.WIDGET_TARGET && firstEntry.getWidget().getId() == WidgetInfo.INVENTORY.getId()) { itemId = firstEntry.getWidget().getItemId(); } else if (firstEntry.isItemOp()) { itemId = firstEntry.getItemId(); } else { return; } int activeOp = 0; final ItemComposition itemComposition = itemManager.getItemComposition(itemId); if (configuringShiftClick) { // For shift-click read the active action off of the item composition, since it may be set by // that even if we have no existing config for it final int shiftClickActionIndex = itemComposition.getShiftClickActionIndex(); if (shiftClickActionIndex >= 0) { activeOp = 1 + shiftClickActionIndex; } else { // Otherwise it is possible that we have Use swap configured Integer config = getItemSwapConfig(true, itemId); if (config != null && config == -1) { activeOp = -1; } } } else { // Apply left click action from configuration Integer config = getItemSwapConfig(false, itemId); if (config != null) { activeOp = config >= 0 ? 1 + config : -1; } } MenuEntry[] entries = event.getMenuEntries(); for (MenuEntry entry : entries) { if (entry.getType() == MenuAction.WIDGET_TARGET && entry.getWidget().getId() == WidgetInfo.INVENTORY.getId() && entry.getWidget().getItemId() == itemId) { entry.setType(MenuAction.RUNELITE); entry.onClick(e -> { log.debug("Set {} item swap for {} to USE", configuringShiftClick ? "shift" : "left", itemId); setItemSwapConfig(configuringShiftClick, itemId, -1); }); if (activeOp == -1) { entry.setOption("* " + entry.getOption()); } } else if (entry.isItemOp() && entry.getItemId() == itemId) { final int itemOp = entry.getItemOp(); entry.setType(MenuAction.RUNELITE); entry.onClick(e -> { log.debug("Set {} item swap config for {} to {}", configuringShiftClick ? "shift" : "left", itemId, itemOp - 1); setItemSwapConfig(configuringShiftClick, itemId, itemOp - 1); }); if (itemOp == activeOp) { entry.setOption("* " + entry.getOption()); } } } client.createMenuEntry(-1) .setOption(RESET) .setTarget(configuringShiftClick ? SHIFT_CLICK_MENU_TARGET : LEFT_CLICK_MENU_TARGET) .setType(MenuAction.RUNELITE) .onClick(e -> unsetItemSwapConfig(configuringShiftClick, itemId)); } private void configureObjectClick(MenuOpened event) { if (!shiftModifier() || !config.objectLeftClickCustomization()) { return; } MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { MenuEntry entry = entries[idx]; if (entry.getType() == MenuAction.EXAMINE_OBJECT) { final ObjectComposition composition = client.getObjectDefinition(entry.getIdentifier()); final String[] actions = composition.getActions(); final Integer swapConfig = getObjectSwapConfig(composition.getId()); final MenuAction currentAction = swapConfig != null ? OBJECT_MENU_TYPES.get(swapConfig) : defaultAction(composition); for (int actionIdx = 0; actionIdx < OBJECT_MENU_TYPES.size(); ++actionIdx) { if (Strings.isNullOrEmpty(actions[actionIdx])) { continue; } final int menuIdx = actionIdx; final MenuAction menuAction = OBJECT_MENU_TYPES.get(actionIdx); if (currentAction == menuAction) { continue; } client.createMenuEntry(idx) .setOption("Swap " + actions[actionIdx]) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to '").append(actions[menuIdx]).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set object swap for {} to {}", composition.getId(), menuAction); final MenuAction defaultAction = defaultAction(composition); if (defaultAction != menuAction) { setObjectSwapConfig(composition.getId(), menuIdx); } else { unsetObjectSwapConfig(composition.getId()); } }); } } } } private Consumer<MenuEntry> walkHereConsumer(boolean shift, NPCComposition composition) { return e -> { final String message = new ChatMessageBuilder() .append("The default ").append(shift ? "shift" : "left").append(" click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to Walk here.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set npc {} click swap for {} to Walk here", shift ? "shift" : "left", composition.getId()); setNpcSwapConfig(shift, composition.getId(), -1); }; } private void configureNpcClick(MenuOpened event) { if (!shiftModifier() || !config.npcLeftClickCustomization()) { return; } MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { final MenuEntry entry = entries[idx]; final MenuAction type = entry.getType(); if (type == MenuAction.EXAMINE_NPC) { final NPC npc = entry.getNpc(); assert npc != null; final NPCComposition composition = npc.getTransformedComposition(); final String[] actions = composition.getActions(); final Integer swapConfig = getNpcSwapConfig(false, composition.getId()); final boolean hasAttack = Arrays.stream(composition.getActions()).anyMatch("Attack"::equalsIgnoreCase); final MenuAction currentAction = swapConfig == null ? // Attackable NPCs always have Attack as the first, last (deprioritized), or when hidden, no, option. // Due to this the default action would be either Attack or the first non-Attack option, based on // the game settings. Since it may be valid to swap an option up to override Attack, even when Attack // is left-click, we cannot assume any default currentAction on attackable NPCs. // Non-attackable NPCS have a predictable default action which we can prevent a swap to if no swap // config is set, which just avoids showing a Swap option on a 1-op NPC, which looks odd. (hasAttack ? null : defaultAction(composition)) : (swapConfig == -1 ? MenuAction.WALK : NPC_MENU_TYPES.get(swapConfig)); for (int actionIdx = 0; actionIdx < NPC_MENU_TYPES.size(); ++actionIdx) { // Attack can be swapped with the in-game settings, and this becomes very confusing if we try // to swap Attack and the game also tries to swap it (by deprioritizing), so just use the in-game // setting. if (Strings.isNullOrEmpty(actions[actionIdx]) || "Attack".equalsIgnoreCase(actions[actionIdx])) { continue; } final int menuIdx = actionIdx; final MenuAction menuAction = NPC_MENU_TYPES.get(actionIdx); if (currentAction == menuAction) { continue; } if ("Knock-Out".equals(actions[actionIdx]) || "Lure".equals(actions[actionIdx])) { // https://secure.runescape.com/m=news/another-message-about-unofficial-clients?oldschool=1 continue; } client.createMenuEntry(idx) .setOption("Swap " + actions[actionIdx]) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left click option for '").append(Text.removeTags(composition.getName())).append("' ") .append("has been set to '").append(actions[menuIdx]).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set npc swap for {} to {}", composition.getId(), menuAction); setNpcSwapConfig(false, composition.getId(), menuIdx); }); } // Walk here swap client.createMenuEntry(idx) .setOption("Swap left click Walk here") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(walkHereConsumer(false, composition)); client.createMenuEntry(idx) .setOption("Swap shift click Walk here") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(walkHereConsumer(true, composition)); if (getNpcSwapConfig(true, composition.getId()) != null || getNpcSwapConfig(false, composition.getId()) != null) { // Reset client.createMenuEntry(idx) .setOption("Reset swap") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default left and shift click options for '").append(Text.removeTags(composition.getName())).append("' ") .append("have been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset npc swap for {}", composition.getId()); unsetNpcSwapConfig(true, composition.getId()); unsetNpcSwapConfig(false, composition.getId()); }); } } } } private void configureWornItems(MenuOpened event) { if (!shiftModifier()) { return; } final MenuEntry[] entries = event.getMenuEntries(); for (int idx = entries.length - 1; idx >= 0; --idx) { final MenuEntry entry = entries[idx]; Widget w = entry.getWidget(); if (w != null && WidgetInfo.TO_GROUP(w.getId()) == WidgetID.EQUIPMENT_GROUP_ID && "Examine".equals(entry.getOption()) && entry.getIdentifier() == 10) { w = w.getChild(1); if (w != null && w.getItemId() > -1) { final ItemComposition itemComposition = itemManager.getItemComposition(w.getItemId()); final Integer leftClickOp = getWornItemSwapConfig(false, itemComposition.getId()); final Integer shiftClickOp = getWornItemSwapConfig(true, itemComposition.getId()); for (int paramId = ParamID.OC_ITEM_OP1, opId = 2; paramId <= ParamID.OC_ITEM_OP8; ++paramId, ++opId) { final String opName = itemComposition.getStringValue(paramId); if (!Strings.isNullOrEmpty(opName)) { if (leftClickOp == null || leftClickOp != opId) { client.createMenuEntry(idx) .setOption("Swap left click " + opName) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(wornItemConsumer(itemComposition, opName, opId, false)); } if (shiftClickOp == null || shiftClickOp != opId) { client.createMenuEntry(idx) .setOption("Swap shift click " + opName) .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(wornItemConsumer(itemComposition, opName, opId, true)); } } } if (leftClickOp != null) { client.createMenuEntry(idx) .setOption("Reset swap left click") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default worn left click option for '").append(itemComposition.getName()).append("' ") .append("has been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset worn item left swap for {}", itemComposition.getName()); unsetWornItemSwapConfig(false, itemComposition.getId()); }); } if (shiftClickOp != null) { client.createMenuEntry(idx) .setOption("Reset swap shift click") .setTarget(entry.getTarget()) .setType(MenuAction.RUNELITE) .onClick(e -> { final String message = new ChatMessageBuilder() .append("The default worn shift click option for '").append(itemComposition.getName()).append("' ") .append("has been reset.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Unset worn item shift swap for {}", itemComposition.getName()); unsetWornItemSwapConfig(true, itemComposition.getId()); }); } } } } } private Consumer<MenuEntry> wornItemConsumer(ItemComposition itemComposition, String opName, int opIdx, boolean shift) { return e -> { final String message = new ChatMessageBuilder() .append("The default worn ").append(shift ? "shift" : "left").append(" click option for '").append(Text.removeTags(itemComposition.getName())).append("' ") .append("has been set to '").append(opName).append("'.") .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); log.debug("Set worn item {} swap for {} to {}", shift ? "shift" : "left", itemComposition.getName(), opIdx); setWornItemSwapConfig(shift, itemComposition.getId(), opIdx); }; } private boolean swapBank(MenuEntry menuEntry, MenuAction type) { if (type != MenuAction.CC_OP && type != MenuAction.CC_OP_LOW_PRIORITY) { return false; } final int widgetGroupId = WidgetInfo.TO_GROUP(menuEntry.getParam1()); final boolean isDepositBoxPlayerInventory = widgetGroupId == WidgetID.DEPOSIT_BOX_GROUP_ID; final boolean isChambersOfXericStorageUnitPlayerInventory = widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_INVENTORY_GROUP_ID; final boolean isGroupStoragePlayerInventory = widgetGroupId == WidgetID.GROUP_STORAGE_INVENTORY_GROUP_ID; // Swap to shift-click deposit behavior // Deposit- op 1 is the current withdraw amount 1/5/10/x for deposit box interface and chambers of xeric storage unit. // Deposit- op 2 is the current withdraw amount 1/5/10/x for bank interface if (shiftModifier() && config.bankDepositShiftClick() != ShiftDepositMode.OFF && type == MenuAction.CC_OP && menuEntry.getIdentifier() == (isDepositBoxPlayerInventory || isGroupStoragePlayerInventory || isChambersOfXericStorageUnitPlayerInventory ? 1 : 2) && (menuEntry.getOption().startsWith("Deposit-") || menuEntry.getOption().startsWith("Store") || menuEntry.getOption().startsWith("Donate"))) { ShiftDepositMode shiftDepositMode = config.bankDepositShiftClick(); final int opId = isDepositBoxPlayerInventory ? shiftDepositMode.getIdentifierDepositBox() : isChambersOfXericStorageUnitPlayerInventory ? shiftDepositMode.getIdentifierChambersStorageUnit() : isGroupStoragePlayerInventory ? shiftDepositMode.getIdentifierGroupStorage() : shiftDepositMode.getIdentifier(); final MenuAction action = opId >= 6 ? MenuAction.CC_OP_LOW_PRIORITY : MenuAction.CC_OP; bankModeSwap(action, opId); return true; } // Swap to shift-click withdraw behavior // Deposit- op 1 is the current withdraw amount 1/5/10/x if (shiftModifier() && config.bankWithdrawShiftClick() != ShiftWithdrawMode.OFF && type == MenuAction.CC_OP && menuEntry.getIdentifier() == 1 && menuEntry.getOption().startsWith("Withdraw")) { ShiftWithdrawMode shiftWithdrawMode = config.bankWithdrawShiftClick(); final MenuAction action; final int opId; if (widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_PRIVATE_GROUP_ID || widgetGroupId == WidgetID.CHAMBERS_OF_XERIC_STORAGE_UNIT_SHARED_GROUP_ID) { action = MenuAction.CC_OP; opId = shiftWithdrawMode.getIdentifierChambersStorageUnit(); } else { action = shiftWithdrawMode.getMenuAction(); opId = shiftWithdrawMode.getIdentifier(); } bankModeSwap(action, opId); return true; } return false; } private void bankModeSwap(MenuAction entryType, int entryIdentifier) { MenuEntry[] menuEntries = client.getMenuEntries(); for (int i = menuEntries.length - 1; i >= 0; --i) { MenuEntry entry = menuEntries[i]; if (entry.getType() == entryType && entry.getIdentifier() == entryIdentifier) { // Raise the priority of the op so it doesn't get sorted later entry.setType(MenuAction.CC_OP); menuEntries[i] = menuEntries[menuEntries.length - 1]; menuEntries[menuEntries.length - 1] = entry; client.setMenuEntries(menuEntries); break; } } } private void swapMenuEntry(MenuEntry[] menuEntries, int index, MenuEntry menuEntry) { final int eventId = menuEntry.getIdentifier(); final MenuAction menuAction = menuEntry.getType(); final String option = Text.removeTags(menuEntry.getOption()).toLowerCase(); final String target = Text.removeTags(menuEntry.getTarget()).toLowerCase(); final NPC hintArrowNpc = client.getHintArrowNpc(); // Don't swap on hint arrow npcs, usually they need "Talk-to" for clues. if (hintArrowNpc != null && hintArrowNpc.getIndex() == eventId && NPC_MENU_TYPES.contains(menuAction)) { return; } final boolean itemOp = menuEntry.isItemOp(); // Custom shift-click item swap if (shiftModifier() && itemOp) { // Special case use shift click due to items not actually containing a "Use" option, making // the client unable to perform the swap itself. if (config.shiftClickCustomization() && !option.equals("use")) { Integer customOption = getItemSwapConfig(true, menuEntry.getItemId()); if (customOption != null && customOption == -1) { swap(menuEntries, "use", target, index, true); } } // don't perform swaps on items when shift is held; instead prefer the client menu swap, which // we may have overwrote return; } // Custom left-click item swap if (itemOp) { Integer swapIndex = getItemSwapConfig(false, menuEntry.getItemId()); if (swapIndex != null) { final int swapAction = swapIndex >= 0 ? 1 + swapIndex : -1; if (swapAction == -1) { swap(menuEntries, "use", target, index, true); } else if (swapAction == menuEntry.getItemOp()) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); } return; } } // Worn items swap Widget w = menuEntry.getWidget(); if (w != null && WidgetInfo.TO_GROUP(w.getId()) == WidgetID.EQUIPMENT_GROUP_ID) { w = w.getChild(1); if (w != null && w.getItemId() > -1) { final Integer wornItemSwapConfig = getWornItemSwapConfig(shiftModifier(), w.getItemId()); if (wornItemSwapConfig != null) { if (wornItemSwapConfig == menuEntry.getIdentifier()) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); } return; } } } if (OBJECT_MENU_TYPES.contains(menuAction)) { // Get multiloc id int objectId = eventId; ObjectComposition objectComposition = client.getObjectDefinition(objectId); if (objectComposition.getImpostorIds() != null) { objectComposition = objectComposition.getImpostor(); objectId = objectComposition.getId(); } Integer customOption = getObjectSwapConfig(objectId); if (customOption != null) { MenuAction swapAction = OBJECT_MENU_TYPES.get(customOption); if (swapAction == menuAction) { swap(optionIndexes, menuEntries, index, menuEntries.length - 1); return; } } } if (NPC_MENU_TYPES.contains(menuAction)) { final NPC npc = menuEntry.getNpc(); assert npc != null; final NPCComposition composition = npc.getTransformedComposition(); Integer customOption = getNpcSwapConfig(shiftModifier(), composition.getId()); if (customOption != null) { // Walk here swap if (customOption == -1) { // we can achieve this by just deprioritizing the normal npc menus menuEntry.setDeprioritized(true); } else { MenuAction swapAction = NPC_MENU_TYPES.get(customOption); if (swapAction == menuAction) { // Advance to the top-most op for this NPC. Normally menuEntries.length - 1 is examine, and swapping // with that works due to it being sorted later, but if other plugins like NPC indicators add additional // menus before examine that are also >1000, like RUNELITE menus, that would result in the >1000 menus being // reordered relative to each other. int i = index; while (i < menuEntries.length - 1 && NPC_MENU_TYPES.contains(menuEntries[i + 1].getType())) { ++i; } swap(optionIndexes, menuEntries, index, i); return; } } } } if (swapBank(menuEntry, menuAction)) { return; } // Built-in swaps Collection<Swap> swaps = this.swaps.get(option); for (Swap swap : swaps) { if (swap.getTargetPredicate().test(target) && swap.getEnabled().get()) { if (swap(menuEntries, swap.getSwappedOption(), target, index, swap.isStrict())) { break; } } } } @Subscribe public void onClientTick(ClientTick clientTick) { // The menu is not rebuilt when it is open, so don't swap or else it will // repeatedly swap entries if (client.getGameState() != GameState.LOGGED_IN || client.isMenuOpen()) { return; } MenuEntry[] menuEntries = client.getMenuEntries(); // Build option map for quick lookup in findIndex int idx = 0; optionIndexes.clear(); for (MenuEntry entry : menuEntries) { String option = Text.removeTags(entry.getOption()).toLowerCase(); optionIndexes.put(option, idx++); } // Perform swaps idx = 0; for (MenuEntry entry : menuEntries) { swapMenuEntry(menuEntries, idx++, entry); } if (config.removeDeadNpcMenus()) { removeDeadNpcs(); } } private void removeDeadNpcs() { MenuEntry[] oldEntries = client.getMenuEntries(); MenuEntry[] newEntries = Arrays.stream(oldEntries) .filter(e -> { final NPC npc = e.getNpc(); if (npc == null) { return true; } final int id = npc.getId(); switch (id) { // These NPCs hit 0hp but don't actually die case NpcID.GARGOYLE: case NpcID.GARGOYLE_413: case NpcID.GARGOYLE_1543: case NpcID.ZYGOMITE: case NpcID.ZYGOMITE_1024: case NpcID.ANCIENT_ZYGOMITE: case NpcID.ROCKSLUG: case NpcID.ROCKSLUG_422: case NpcID.DESERT_LIZARD: case NpcID.DESERT_LIZARD_460: case NpcID.DESERT_LIZARD_461: case NpcID.ICE_DEMON: case NpcID.ICE_DEMON_7585: return true; default: return !npc.isDead(); } }) .toArray(MenuEntry[]::new); if (oldEntries.length != newEntries.length) { client.setMenuEntries(newEntries); } } @Subscribe public void onPostItemComposition(PostItemComposition event) { if (!config.shiftClickCustomization()) { // since shift-click is done by the client we have to check if our shift click customization is on // prior to altering the item shift click action index. return; } ItemComposition itemComposition = event.getItemComposition(); Integer option = getItemSwapConfig(true, itemComposition.getId()); if (option != null && option < itemComposition.getInventoryActions().length) { itemComposition.setShiftClickActionIndex(option); } } private boolean swap(MenuEntry[] menuEntries, String option, String target, int index, boolean strict) { // find option to swap with int optionIdx = findIndex(menuEntries, index, option, target, strict); if (optionIdx >= 0) { swap(optionIndexes, menuEntries, optionIdx, index); return true; } return false; } private int findIndex(MenuEntry[] entries, int limit, String option, String target, boolean strict) { if (strict) { List<Integer> indexes = optionIndexes.get(option); // We want the last index which matches the target, as that is what is top-most // on the menu for (int i = indexes.size() - 1; i >= 0; --i) { int idx = indexes.get(i); MenuEntry entry = entries[idx]; String entryTarget = Text.removeTags(entry.getTarget()).toLowerCase(); // Limit to the last index which is prior to the current entry if (idx < limit && entryTarget.equals(target)) { return idx; } } } else { // Without strict matching we have to iterate all entries up to the current limit... for (int i = limit - 1; i >= 0; i--) { MenuEntry entry = entries[i]; String entryOption = Text.removeTags(entry.getOption()).toLowerCase(); String entryTarget = Text.removeTags(entry.getTarget()).toLowerCase(); if (entryOption.contains(option.toLowerCase()) && entryTarget.equals(target)) { return i; } } } return -1; } private void swap(ArrayListMultimap<String, Integer> optionIndexes, MenuEntry[] entries, int index1, int index2) { if (index1 == index2) { return; } MenuEntry entry1 = entries[index1], entry2 = entries[index2]; entries[index1] = entry2; entries[index2] = entry1; // Item op4 and op5 are CC_OP_LOW_PRIORITY so they get added underneath Use, // but this also causes them to get sorted after client tick. Change them to // CC_OP to avoid this. if (entry1.isItemOp() && entry1.getType() == MenuAction.CC_OP_LOW_PRIORITY) { entry1.setType(MenuAction.CC_OP); } if (entry2.isItemOp() && entry2.getType() == MenuAction.CC_OP_LOW_PRIORITY) { entry2.setType(MenuAction.CC_OP); } client.setMenuEntries(entries); // Update optionIndexes String option1 = Text.removeTags(entry1.getOption()).toLowerCase(), option2 = Text.removeTags(entry2.getOption()).toLowerCase(); List<Integer> list1 = optionIndexes.get(option1), list2 = optionIndexes.get(option2); // call remove(Object) instead of remove(int) list1.remove((Integer) index1); list2.remove((Integer) index2); sortedInsert(list1, index2); sortedInsert(list2, index1); } private static <T extends Comparable<? super T>> void sortedInsert(List<T> list, T value) // NOPMD: UnusedPrivateMethod: false positive { int idx = Collections.binarySearch(list, value); list.add(idx < 0 ? -idx - 1 : idx, value); } private void removeCusomizationMenus() { // Shift click menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_SC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_SC); // Left click menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_LC); menuManager.removeManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_LC); } private void rebuildCustomizationMenus() { removeCusomizationMenus(); if (configuringLeftClick) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_LC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_LC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_LC, this::save); } else if (configuringShiftClick) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_SAVE_SC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_SAVE_SC, this::save); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_SAVE_SC, this::save); } else { // Left click if (config.leftClickCustomization()) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_LC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_LC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_LC, this::configure); } // Shift click if (config.shiftClickCustomization()) { menuManager.addManagedCustomMenu(FIXED_INVENTORY_TAB_CONFIGURE_SC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_BOTTOM_LINE_INVENTORY_TAB_CONFIGURE_SC, this::configure); menuManager.addManagedCustomMenu(RESIZABLE_INVENTORY_TAB_CONFIGURE_SC, this::configure); } } } private boolean shiftModifier() { return client.isKeyPressed(KeyCode.KC_SHIFT); } private void save(MenuEntry menuEntry) { configuringLeftClick = configuringShiftClick = false; rebuildCustomizationMenus(); } private void configure(MenuEntry menuEntry) { String target = Text.removeTags(menuEntry.getTarget()); configuringShiftClick = target.equals(SHIFT_CLICK_MENU_TARGET); configuringLeftClick = target.equals(LEFT_CLICK_MENU_TARGET); rebuildCustomizationMenus(); } private Integer getObjectSwapConfig(int objectId) { String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setObjectSwapConfig(int objectId, int index) { configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId, index); } private void unsetObjectSwapConfig(int objectId) { configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, OBJECT_KEY_PREFIX + objectId); } private static MenuAction defaultAction(ObjectComposition objectComposition) { String[] actions = objectComposition.getActions(); for (int i = 0; i < OBJECT_MENU_TYPES.size(); ++i) { if (!Strings.isNullOrEmpty(actions[i])) { return OBJECT_MENU_TYPES.get(i); } } return null; } private Integer getNpcSwapConfig(boolean shift, int npcId) { String config = configManager.getConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId); if (config == null || config.isEmpty()) { return null; } return Integer.parseInt(config); } private void setNpcSwapConfig(boolean shift, int npcId, int index) { configManager.setConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId, index); } private void unsetNpcSwapConfig(boolean shift, int npcId) { configManager.unsetConfiguration(MenuEntrySwapperConfig.GROUP, (shift ? NPC_SHIFT_KEY_PREFIX : NPC_KEY_PREFIX) + npcId); } private static MenuAction defaultAction(NPCComposition composition) { String[] actions = composition.getActions(); for (int i = 0; i < NPC_MENU_TYPES.size(); ++i) { if (!Strings.isNullOrEmpty(actions[i]) && !actions[i].equalsIgnoreCase("Attack")) { return NPC_MENU_TYPES.get(i); } } return null; } }
menu swapper: disable pmd check
runelite-client/src/main/java/net/runelite/client/plugins/menuentryswapper/MenuEntrySwapperPlugin.java
menu swapper: disable pmd check
<ide><path>unelite-client/src/main/java/net/runelite/client/plugins/menuentryswapper/MenuEntrySwapperPlugin.java <ide> final NPC npc = entry.getNpc(); <ide> assert npc != null; <ide> final NPCComposition composition = npc.getTransformedComposition(); <add> assert composition != null; <ide> final String[] actions = composition.getActions(); <ide> <ide> final Integer swapConfig = getNpcSwapConfig(false, composition.getId()); <ide> .setType(MenuAction.RUNELITE) <ide> .onClick(walkHereConsumer(true, composition)); <ide> <del> if (getNpcSwapConfig(true, composition.getId()) != null || getNpcSwapConfig(false, composition.getId()) != null) <add> if (getNpcSwapConfig(true, composition.getId()) != null || getNpcSwapConfig(false, composition.getId()) != null) // NOPMD: BrokenNullCheck <ide> { <ide> // Reset <ide> client.createMenuEntry(idx)
Java
lgpl-2.1
ad3774d09532350417887a25d9802b6a920cd90c
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2002-04 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // FILE: c:/projects/jetel/org/jetel/data/DelimitedDataParser.java package org.jetel.data.parser; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.io.*; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.BadDataFormatExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.metadata.*; import org.jetel.util.StringUtils; /** * Parsing delimited text data. Supports delimiters with the length of up to 32 * characters. Delimiter for each individual field must be specified - through * metadata definition. The maximum length of one parseable field is denoted by * <b>FIELD_BUFFER_LENGT</b> . Parser handles quoted strings (single or double). * This class is using the new IO (NIO) features * introduced in Java 1.4 - directly mapped byte buffers & character * encoders/decoders * *@author D.Pavlis *@since March 27, 2002 *@see Parser *@see org.jetel.data.Defaults * @revision $Revision$ */ public class DelimitedDataParserNIO implements Parser { private String charSet = null; private BadDataFormatExceptionHandler handlerBDFE; private ByteBuffer dataBuffer; private CharBuffer charBuffer; private CharBuffer fieldStringBuffer; private char[] delimiterCandidateBuffer; private DataRecordMetadata metadata; private ReadableByteChannel reader; private CharsetDecoder decoder; private int recordCounter; private char[][] delimiters; private char[] fieldTypes; private boolean isEof; private boolean skipRows=false; // this will be added as a parameter to constructor private boolean handleQuotedStrings = true; // Attributes // maximum length of delimiter private final static int DELIMITER_CANDIDATE_BUFFER_LENGTH = 32; // Associations // Operations /** * Constructor for the DelimitedDataParser object. With default size and * default character encoding. * *@since March 28, 2002 */ public DelimitedDataParserNIO() { this(Defaults.DataParser.DEFAULT_CHARSET_DECODER); } /** * Constructor for the DelimitedDataParser object * *@param charsetDecoder Charset Decoder used for converting input data into * UNICODE chars *@since March 28, 2002 */ public DelimitedDataParserNIO(String charsetDecoder) { this.charSet = charsetDecoder; dataBuffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); charBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); fieldStringBuffer = CharBuffer.allocate(Defaults.DataParser.FIELD_BUFFER_LENGTH); delimiterCandidateBuffer = new char [DELIMITER_CANDIDATE_BUFFER_LENGTH]; decoder = Charset.forName(charsetDecoder).newDecoder(); } /** * Returs next data record parsed from input stream or NULL if no more data * available * *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext() throws JetelException { // create a new data record DataRecord record = new DataRecord(metadata); record.init(); record = parseNext(record); if(handlerBDFE != null ) { //use handler only if configured while(handlerBDFE.isThrowException()) { handlerBDFE.handleException(record); //record.init(); //redundant record = parseNext(record); } } return record; } /** * Returs next data record parsed from input stream or NULL if no more data * available The specified DataRecord's fields are altered to contain new * values. * *@param record Description of Parameter *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(handlerBDFE != null ) { //use handler only if configured while(handlerBDFE.isThrowException()) { handlerBDFE.handleException(record); //record.init(); //redundant record = parseNext(record); } } return record; } /** * An operation that opens/initializes parser. * *@param in InputStream of delimited text data *@param _metadata Metadata describing the structure of data *@since March 27, 2002 */ public void open(Object in, DataRecordMetadata metadata) { DataFieldMetadata fieldMetadata; this.metadata = metadata; reader = ((FileInputStream) in).getChannel(); // create array of delimiters & initialize them delimiters = new char[metadata.getNumFields()][]; fieldTypes = new char[metadata.getNumFields()]; for (int i = 0; i < metadata.getNumFields(); i++) { fieldMetadata = metadata.getField(i); delimiters[i] = fieldMetadata.getDelimiter().toCharArray(); fieldTypes[i] = fieldMetadata.getType(); // we handle only one character delimiters } decoder.reset();// reset CharsetDecoder dataBuffer.clear(); dataBuffer.flip(); charBuffer.clear(); charBuffer.flip(); recordCounter = 1;// reset record counter isEof=false; } /** * Description of the Method * *@since May 2, 2002 */ public void close() { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * Assembles error message when exception occures during parsing * *@param exceptionMessage message from exception getMessage() call *@param recNo recordNumber *@param fieldNo fieldNumber *@return error message *@since September 19, 2002 */ private String getErrorMessage(String exceptionMessage,CharSequence value, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record #"); message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); if (value!=null){ message.append(" value \"").append(value).append("\""); } return message.toString(); } /** * Description of the Method * *@return Description of the Returned Value *@exception IOException Description of Exception *@since May 13, 2002 */ private int readChar() throws IOException { if (charBuffer.hasRemaining()) { return charBuffer.get(); } if (isEof) return -1; charBuffer.clear(); if (dataBuffer.hasRemaining()) dataBuffer.compact(); else dataBuffer.clear(); if (reader.read(dataBuffer)==-1){ isEof=true; } dataBuffer.flip(); if (decoder.decode(dataBuffer,charBuffer,isEof)==CoderResult.UNDERFLOW){ //try to load additional data dataBuffer.compact(); if (reader.read(dataBuffer)==-1){ isEof=true; } dataBuffer.flip(); decoder.decode(dataBuffer,charBuffer,isEof); } if (isEof){ decoder.flush(charBuffer); } charBuffer.flip(); return charBuffer.hasRemaining() ? charBuffer.get() : -1; } /** * An operation that does ... * *@param record Description of Parameter *@return Next DataRecord (parsed from input data) or null if * no more records available *@exception IOException Description of Exception *@since March 27, 2002 */ private DataRecord parseNext(DataRecord record) throws JetelException { int result; int fieldCounter = 0; int character; int totalCharCounter = 0; int delimiterPosition; long size = 0; int charCounter; boolean isWithinQuotes; char quoteChar=' '; // populate all data fields while (fieldCounter < metadata.getNumFields()) { // we clear our buffer fieldStringBuffer.clear(); character = 0; isWithinQuotes=false; // read data till we reach delimiter, end of file or exceed buffer size // exceeded buffer is indicated by BufferOverflowException charCounter = 0; delimiterPosition = 0; try { while ((character = readChar()) != -1) { // causes problem when composed delimiter "\r\n" is used // if(character=='\r') //fix for new line being \r\n // continue; totalCharCounter++; // handle quoted strings if (handleQuotedStrings && StringUtils.isQuoteChar((char)character)){ if (!isWithinQuotes){ if (charCounter==0){ quoteChar=(char)character; isWithinQuotes=true; } }else if (quoteChar==(char)character){ isWithinQuotes=false; } } if ((result = is_delimiter((char) character, fieldCounter, delimiterPosition,isWithinQuotes)) == 1) { /* * DELIMITER */ break; } else if (result == 0) { /* * NOT A DELIMITER */ if (delimiterPosition > 0) { fieldStringBuffer.put(delimiterCandidateBuffer,0,delimiterPosition); } else { try{ fieldStringBuffer.put((char) character); }catch(BufferOverflowException ex){ throw new IOException("Field too long or can not find delimiter ["+String.valueOf(delimiters[fieldCounter])+"]"); } } delimiterPosition = 0; } else { /* * CAN'T DECIDE DELIMITER */ delimiterCandidateBuffer[delimiterPosition]=((char) character); delimiterPosition++; } charCounter++; } if ((character == -1) && (totalCharCounter > 1)) { //- incomplete record - do something throw new RuntimeException("Incomplete record"); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(getErrorMessage(ex.getClass().getName()+":"+ex.getMessage(),null, recordCounter, fieldCounter),ex); } // did we have EOF situation ? if (character == -1) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); throw new JetelException(e.getMessage()); } return null; } // set field's value // are we skipping this row/field ? if (!skipRows){ fieldStringBuffer.flip(); populateField(record, fieldCounter, fieldStringBuffer); } fieldCounter++; } recordCounter++; return record; } /** * Description of the Method * *@param record Description of Parameter *@param fieldNum Description of Parameter *@param data Description of Parameter *@since March 28, 2002 */ private void populateField(DataRecord record, int fieldNum, CharBuffer data) { try { record.getField(fieldNum).fromString(buffer2String(data, fieldNum,handleQuotedStrings)); } catch (BadDataFormatException bdfe) { if(handlerBDFE != null ) { //use handler only if configured handlerBDFE.populateFieldFailure(getErrorMessage(bdfe.getMessage(),data,recordCounter, fieldNum), record,fieldNum,data.toString()); } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(),data,recordCounter, fieldNum)); } } catch (Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(),null,recordCounter, fieldNum),ex); } } /** * Transfers CharBuffer into string and handles quoting of strings (removes quotes) * *@param buffer Character buffer to work on *@param removeQuotes true/false remove quotation characters *@return String with quotes removed if specified */ private String buffer2String(CharBuffer buffer,int fieldNum, boolean removeQuotes) { if (removeQuotes && buffer.hasRemaining() && metadata.getField(fieldNum).getType()== DataFieldMetadata.STRING_FIELD) { /* if first & last characters are quotes (and quoted is at least one character, remove quotes */ if (StringUtils.isQuoteChar(buffer.charAt(0))) { if (StringUtils.isQuoteChar(buffer.charAt(buffer.limit()-1))) { if (buffer.remaining()>2){ return buffer.subSequence(1, buffer.limit() - 1).toString(); }else{ return ""; //empty string after quotes removed } } } } return buffer.toString(); } /** * Decides whether delimiter was encountered * *@param character character to compare with delimiter *@param fieldCounter delimiter for which field *@param delimiterPosition current position within delimiter string *@return 1 if delimiter matched; -1 if can't decide yet; 0 if not part of delimiter */ private int is_delimiter(char character, int fieldCounter, int delimiterPosition, boolean isWithinQuotes) { if (isWithinQuotes){ return 0; } if (character == delimiters[fieldCounter][delimiterPosition]) { if (delimiterPosition == delimiters[fieldCounter].length - 1) { return 1; // whole delimiter matched } else { return -1; // can't decide } } else { return 0; // not a match } } /** * @param handler */ public void addBDFHandler(BadDataFormatExceptionHandler handler) { this.handlerBDFE = handler; } /** * Returns charset name of this parser * @return Returns name of the charset used to construct or null if none was specified */ public String getCharsetName() { return(this.charSet); } /** * Returns data policy type for this parser * @return Data policy type or null if none was specified */ public String getBDFHandlerPolicyType() { if (this.handlerBDFE != null) { return(this.handlerBDFE.getPolicyType()); } else { return(null); } } /** * @return Returns the skipRows. */ public boolean isSkipRows() { return skipRows; } /** * @param skipRows The skipRows to set. */ public void setSkipRows(boolean skipRows) { this.skipRows = skipRows; } } /* * end class DelimitedDataParser */
cloveretl.engine/src/org/jetel/data/parser/DelimitedDataParserNIO.java
/* * jETeL/Clover - Java based ETL application framework. * Copyright (C) 2002-04 David Pavlis <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // FILE: c:/projects/jetel/org/jetel/data/DelimitedDataParser.java package org.jetel.data.parser; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.io.*; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.BadDataFormatExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.metadata.*; import org.jetel.util.StringUtils; /** * Parsing delimited text data. Supports delimiters with the length of up to 32 * characters. Delimiter for each individual field must be specified - through * metadata definition. The maximum length of one parseable field is denoted by * <b>FIELD_BUFFER_LENGT</b> . Parser handles quoted strings (single or double). * This class is using the new IO (NIO) features * introduced in Java 1.4 - directly mapped byte buffers & character * encoders/decoders * *@author D.Pavlis *@since March 27, 2002 *@see Parser *@see org.jetel.data.Defaults * @revision $Revision$ */ public class DelimitedDataParserNIO implements Parser { private String charSet = null; private BadDataFormatExceptionHandler handlerBDFE; private ByteBuffer dataBuffer; private CharBuffer charBuffer; private CharBuffer fieldStringBuffer; private char[] delimiterCandidateBuffer; private DataRecordMetadata metadata; private ReadableByteChannel reader; private CharsetDecoder decoder; private int recordCounter; private char[] delimiters[]; private char fieldTypes[]; private boolean isEof; private boolean skipRows=false; // this will be added as a parameter to constructor private boolean handleQuotedStrings = true; // Attributes // maximum length of delimiter private final static int DELIMITER_CANDIDATE_BUFFER_LENGTH = 32; // Associations // Operations /** * Constructor for the DelimitedDataParser object. With default size and * default character encoding. * *@since March 28, 2002 */ public DelimitedDataParserNIO() { this(Defaults.DataParser.DEFAULT_CHARSET_DECODER); } /** * Constructor for the DelimitedDataParser object * *@param charsetDecoder Charset Decoder used for converting input data into * UNICODE chars *@since March 28, 2002 */ public DelimitedDataParserNIO(String charsetDecoder) { this.charSet = charsetDecoder; dataBuffer = ByteBuffer.allocateDirect(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); charBuffer = CharBuffer.allocate(Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE); fieldStringBuffer = CharBuffer.allocate(Defaults.DataParser.FIELD_BUFFER_LENGTH); delimiterCandidateBuffer = new char [DELIMITER_CANDIDATE_BUFFER_LENGTH]; decoder = Charset.forName(charsetDecoder).newDecoder(); } /** * Returs next data record parsed from input stream or NULL if no more data * available * *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext() throws JetelException { // create a new data record DataRecord record = new DataRecord(metadata); record.init(); record = parseNext(record); if(handlerBDFE != null ) { //use handler only if configured while(handlerBDFE.isThrowException()) { handlerBDFE.handleException(record); //record.init(); //redundant record = parseNext(record); } } return record; } /** * Returs next data record parsed from input stream or NULL if no more data * available The specified DataRecord's fields are altered to contain new * values. * *@param record Description of Parameter *@return The Next value *@exception IOException Description of Exception *@since May 2, 2002 */ public DataRecord getNext(DataRecord record) throws JetelException { record = parseNext(record); if(handlerBDFE != null ) { //use handler only if configured while(handlerBDFE.isThrowException()) { handlerBDFE.handleException(record); //record.init(); //redundant record = parseNext(record); } } return record; } /** * An operation that opens/initializes parser. * *@param in InputStream of delimited text data *@param _metadata Metadata describing the structure of data *@since March 27, 2002 */ public void open(Object in, DataRecordMetadata metadata) { DataFieldMetadata fieldMetadata; this.metadata = metadata; reader = ((FileInputStream) in).getChannel(); // create array of delimiters & initialize them delimiters = new char[metadata.getNumFields()][]; fieldTypes = new char[metadata.getNumFields()]; for (int i = 0; i < metadata.getNumFields(); i++) { fieldMetadata = metadata.getField(i); delimiters[i] = fieldMetadata.getDelimiter().toCharArray(); fieldTypes[i] = fieldMetadata.getType(); // we handle only one character delimiters } decoder.reset();// reset CharsetDecoder dataBuffer.clear(); dataBuffer.flip(); charBuffer.clear(); charBuffer.flip(); recordCounter = 1;// reset record counter isEof=false; } /** * Description of the Method * *@since May 2, 2002 */ public void close() { if (reader != null) { try { reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } } /** * Assembles error message when exception occures during parsing * *@param exceptionMessage message from exception getMessage() call *@param recNo recordNumber *@param fieldNo fieldNumber *@return error message *@since September 19, 2002 */ private String getErrorMessage(String exceptionMessage,CharSequence value, int recNo, int fieldNo) { StringBuffer message = new StringBuffer(); message.append(exceptionMessage); message.append(" when parsing record #"); message.append(recordCounter); message.append(" field "); message.append(metadata.getField(fieldNo).getName()); if (value!=null){ message.append(" value \"").append(value).append("\""); } return message.toString(); } /** * Description of the Method * *@return Description of the Returned Value *@exception IOException Description of Exception *@since May 13, 2002 */ private int readChar() throws IOException { if (charBuffer.hasRemaining()) { return charBuffer.get(); } if (isEof) return -1; charBuffer.clear(); if (dataBuffer.hasRemaining()) dataBuffer.compact(); else dataBuffer.clear(); if (reader.read(dataBuffer)==-1){ isEof=true; } dataBuffer.flip(); if (decoder.decode(dataBuffer,charBuffer,isEof)==CoderResult.UNDERFLOW){ //try to load additional data dataBuffer.compact(); if (reader.read(dataBuffer)==-1){ isEof=true; } dataBuffer.flip(); decoder.decode(dataBuffer,charBuffer,isEof); } if (isEof){ decoder.flush(charBuffer); } charBuffer.flip(); return charBuffer.hasRemaining() ? charBuffer.get() : -1; } /** * An operation that does ... * *@param record Description of Parameter *@return Next DataRecord (parsed from input data) or null if * no more records available *@exception IOException Description of Exception *@since March 27, 2002 */ private DataRecord parseNext(DataRecord record) throws JetelException { int result; int fieldCounter = 0; int character; int totalCharCounter = 0; int delimiterPosition; long size = 0; int charCounter; boolean isWithinQuotes; char quoteChar=' '; // populate all data fields while (fieldCounter < metadata.getNumFields()) { // we clear our buffer fieldStringBuffer.clear(); character = 0; isWithinQuotes=false; // read data till we reach delimiter, end of file or exceed buffer size // exceeded buffer is indicated by BufferOverflowException charCounter = 0; delimiterPosition = 0; try { while ((character = readChar()) != -1) { // causes problem when composed delimiter "\r\n" is used // if(character=='\r') //fix for new line being \r\n // continue; totalCharCounter++; // handle quoted strings if (handleQuotedStrings && StringUtils.isQuoteChar((char)character)){ if (!isWithinQuotes){ if (charCounter==0){ quoteChar=(char)character; isWithinQuotes=true; } }else if (quoteChar==(char)character){ isWithinQuotes=false; } } if ((result = is_delimiter((char) character, fieldCounter, delimiterPosition,isWithinQuotes)) == 1) { /* * DELIMITER */ break; } else if (result == 0) { /* * NOT A DELIMITER */ if (delimiterPosition > 0) { fieldStringBuffer.put(delimiterCandidateBuffer,0,delimiterPosition); } else { try{ fieldStringBuffer.put((char) character); }catch(BufferOverflowException ex){ throw new IOException("Field too long or can not find delimiter ["+delimiters[fieldCounter]+"]"); } } delimiterPosition = 0; } else { /* * CAN'T DECIDE DELIMITER */ delimiterCandidateBuffer[delimiterPosition]=((char) character); delimiterPosition++; } charCounter++; } if ((character == -1) && (totalCharCounter > 1)) { //- incomplete record - do something throw new RuntimeException("Incomplete record"); } } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(getErrorMessage(ex.getClass().getName()+":"+ex.getMessage(),null, recordCounter, fieldCounter),ex); } // did we have EOF situation ? if (character == -1) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); throw new JetelException(e.getMessage()); } return null; } // set field's value // are we skipping this row/field ? if (!skipRows){ fieldStringBuffer.flip(); populateField(record, fieldCounter, fieldStringBuffer); } fieldCounter++; } recordCounter++; return record; } /** * Description of the Method * *@param record Description of Parameter *@param fieldNum Description of Parameter *@param data Description of Parameter *@since March 28, 2002 */ private void populateField(DataRecord record, int fieldNum, CharBuffer data) { try { record.getField(fieldNum).fromString(buffer2String(data, fieldNum,handleQuotedStrings)); } catch (BadDataFormatException bdfe) { if(handlerBDFE != null ) { //use handler only if configured handlerBDFE.populateFieldFailure(getErrorMessage(bdfe.getMessage(),data,recordCounter, fieldNum), record,fieldNum,data.toString()); } else { throw new RuntimeException(getErrorMessage(bdfe.getMessage(),data,recordCounter, fieldNum)); } } catch (Exception ex) { throw new RuntimeException(getErrorMessage(ex.getMessage(),null,recordCounter, fieldNum),ex); } } /** * Transfers CharBuffer into string and handles quoting of strings (removes quotes) * *@param buffer Character buffer to work on *@param removeQuotes true/false remove quotation characters *@return String with quotes removed if specified */ private String buffer2String(CharBuffer buffer,int fieldNum, boolean removeQuotes) { if (removeQuotes && buffer.hasRemaining() && metadata.getField(fieldNum).getType()== DataFieldMetadata.STRING_FIELD) { /* if first & last characters are quotes (and quoted is at least one character, remove quotes */ if (StringUtils.isQuoteChar(buffer.charAt(0))) { if (StringUtils.isQuoteChar(buffer.charAt(buffer.limit()-1))) { if (buffer.remaining()>2){ return buffer.subSequence(1, buffer.limit() - 1).toString(); }else{ return ""; //empty string after quotes removed } } } } return buffer.toString(); } /** * Decides whether delimiter was encountered * *@param character character to compare with delimiter *@param fieldCounter delimiter for which field *@param delimiterPosition current position within delimiter string *@return 1 if delimiter matched; -1 if can't decide yet; 0 if not part of delimiter */ private int is_delimiter(char character, int fieldCounter, int delimiterPosition, boolean isWithinQuotes) { if (isWithinQuotes){ return 0; } if (character == delimiters[fieldCounter][delimiterPosition]) { if (delimiterPosition == delimiters[fieldCounter].length - 1) { return 1; // whole delimiter matched } else { return -1; // can't decide } } else { return 0; // not a match } } /** * @param handler */ public void addBDFHandler(BadDataFormatExceptionHandler handler) { this.handlerBDFE = handler; } /** * Returns charset name of this parser * @return Returns name of the charset used to construct or null if none was specified */ public String getCharsetName() { return(this.charSet); } /** * Returns data policy type for this parser * @return Data policy type or null if none was specified */ public String getBDFHandlerPolicyType() { if (this.handlerBDFE != null) { return(this.handlerBDFE.getPolicyType()); } else { return(null); } } /** * @return Returns the skipRows. */ public boolean isSkipRows() { return skipRows; } /** * @param skipRows The skipRows to set. */ public void setSkipRows(boolean skipRows) { this.skipRows = skipRows; } } /* * end class DelimitedDataParser */
Cosmetic changes. git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@752 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/data/parser/DelimitedDataParserNIO.java
Cosmetic changes.
<ide><path>loveretl.engine/src/org/jetel/data/parser/DelimitedDataParserNIO.java <ide> private ReadableByteChannel reader; <ide> private CharsetDecoder decoder; <ide> private int recordCounter; <del> private char[] delimiters[]; <del> private char fieldTypes[]; <add> private char[][] delimiters; <add> private char[] fieldTypes; <ide> private boolean isEof; <ide> private boolean skipRows=false; <ide> <ide> try{ <ide> fieldStringBuffer.put((char) character); <ide> }catch(BufferOverflowException ex){ <del> throw new IOException("Field too long or can not find delimiter ["+delimiters[fieldCounter]+"]"); <add> throw new IOException("Field too long or can not find delimiter ["+String.valueOf(delimiters[fieldCounter])+"]"); <ide> } <ide> } <ide> delimiterPosition = 0;
JavaScript
mit
ca94887fbc5edf4ccec2a007d5066f8181dab270
0
pjleonard37/philly-hoods,davewalk/philly-hoods,pjleonard37/philly-hoods,davewalk/philly-hoods,davewalk/philly-hoods,pjleonard37/philly-hoods,pjleonard37/philly-hoods
var db = require('../lib/db'); exports.get = function (req, res, next) { var editedName = req.params.name.toUpperCase(); var editedName = editedName.replace(' ', '_'); db.fromName(editedName, function (err, result) { if (err) { res.json(500, {error: 'Error attempting to get neighborhood: ' + err}); } else { res.json(200, {request: { neighborhood: req.params.name }, results: result}); } }); return next(); }; exports.list = function (req, res, next) { db.list(function (err, result) { if (err) { res.json(500, {error: 'Error attempting to get neighborhoods'}); } else { var results = []; for (var key in result) { var val = result[key]['name']; results.push(val); } res.json(200, {request: 'neighborhoods', results: results}); } }); return next(); };
routes/neighborhoods.js
var db = require('../lib/db'); exports.get = function (req, res, next) { var editedName = req.params.name.toUpperCase(); var editedName = editedName.replace(' ', '_'); db.fromName(editedName, function (err, result) { if (err) { res.json(500, {error: 'Error attempting to get neighborhood: ' + err}); } else { res.json(200, {request: { neighborhood: req.params.name }, results: result}); } }); return next(); }; exports.list = function (req, res, next) { db.list(function (err, result) { if (err) { res.json(500, {error: 'Error attempting to get neighborhoods'}); } else { var results = []; for (var key in result) { var val = result[key]['name']; console.log(val); results.push(val); } res.json(200, {request: 'neighborhoods', results: results}); } }); return next(); };
Removing console log
routes/neighborhoods.js
Removing console log
<ide><path>outes/neighborhoods.js <ide> <ide> for (var key in result) { <ide> var val = result[key]['name']; <del> console.log(val); <ide> results.push(val); <ide> } <ide> res.json(200, {request: 'neighborhoods', results: results});
Java
apache-2.0
cd8f6f781b70ca6476f92320b631122fd29930b4
0
vitvitvit/java_learning,vitvitvit/java_learning
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.GroupData; public class GroupModificationTests extends TestBase{ @Test public void testGroupModification() { app.getNavigationHelper().gotoGroupPage(); if (! app.getGroupHelper().isThereAGroup()) { app.getGroupHelper().createGroup(new GroupData("new group3", null, null)); } app.getGroupHelper().selectGroup(); app.getGroupHelper().initGroupModification(); app.getGroupHelper().fillGroupForm(new GroupData("modify group2", "t2", null)); app.getGroupHelper().submitGroupModification(); app.getGroupHelper().returnToGroupPage(); } }
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupModificationTests.java
package ru.stqa.pft.addressbook.tests; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.GroupData; public class GroupModificationTests extends TestBase{ @Test public void testGroupModification() { app.getNavigationHelper().gotoGroupPage(); app.getGroupHelper().selectGroup(); app.getGroupHelper().initGroupModification(); app.getGroupHelper().fillGroupForm(new GroupData("modify group2", "t2", null)); app.getGroupHelper().submitGroupModification(); app.getGroupHelper().returnToGroupPage(); } }
проверка наличия группы перед модификацией
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupModificationTests.java
проверка наличия группы перед модификацией
<ide><path>ddressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/GroupModificationTests.java <ide> @Test <ide> public void testGroupModification() { <ide> app.getNavigationHelper().gotoGroupPage(); <add> if (! app.getGroupHelper().isThereAGroup()) { <add> app.getGroupHelper().createGroup(new GroupData("new group3", null, null)); <add> } <ide> app.getGroupHelper().selectGroup(); <ide> app.getGroupHelper().initGroupModification(); <ide> app.getGroupHelper().fillGroupForm(new GroupData("modify group2", "t2", null));
Java
bsd-3-clause
baba9d6b4756ef77dbd5b1de5fa78260ee522f08
0
g-rocket/jmonkeyengine,skapi1992/jmonkeyengine,bsmr-java/jmonkeyengine,Georgeto/jmonkeyengine,amit2103/jmonkeyengine,wrvangeest/jmonkeyengine,nickschot/jmonkeyengine,amit2103/jmonkeyengine,aaronang/jmonkeyengine,phr00t/jmonkeyengine,shurun19851206/jMonkeyEngine,weilichuang/jmonkeyengine,danteinforno/jmonkeyengine,sandervdo/jmonkeyengine,wrvangeest/jmonkeyengine,weilichuang/jmonkeyengine,wrvangeest/jmonkeyengine,shurun19851206/jMonkeyEngine,jMonkeyEngine/jmonkeyengine,mbenson/jmonkeyengine,amit2103/jmonkeyengine,atomixnmc/jmonkeyengine,shurun19851206/jMonkeyEngine,weilichuang/jmonkeyengine,phr00t/jmonkeyengine,bertleft/jmonkeyengine,rbottema/jmonkeyengine,GreenCubes/jmonkeyengine,OpenGrabeso/jmonkeyengine,mbenson/jmonkeyengine,nickschot/jmonkeyengine,Georgeto/jmonkeyengine,GreenCubes/jmonkeyengine,InShadow/jmonkeyengine,sandervdo/jmonkeyengine,Georgeto/jmonkeyengine,Georgeto/jmonkeyengine,yetanotherindie/jMonkey-Engine,bsmr-java/jmonkeyengine,amit2103/jmonkeyengine,d235j/jmonkeyengine,atomixnmc/jmonkeyengine,g-rocket/jmonkeyengine,danteinforno/jmonkeyengine,skapi1992/jmonkeyengine,tr0k/jmonkeyengine,jMonkeyEngine/jmonkeyengine,davidB/jmonkeyengine,skapi1992/jmonkeyengine,yetanotherindie/jMonkey-Engine,davidB/jmonkeyengine,g-rocket/jmonkeyengine,atomixnmc/jmonkeyengine,shurun19851206/jMonkeyEngine,yetanotherindie/jMonkey-Engine,davidB/jmonkeyengine,atomixnmc/jmonkeyengine,yetanotherindie/jMonkey-Engine,GreenCubes/jmonkeyengine,delftsre/jmonkeyengine,olafmaas/jmonkeyengine,danteinforno/jmonkeyengine,tr0k/jmonkeyengine,weilichuang/jmonkeyengine,olafmaas/jmonkeyengine,davidB/jmonkeyengine,yetanotherindie/jMonkey-Engine,danteinforno/jmonkeyengine,atomixnmc/jmonkeyengine,bsmr-java/jmonkeyengine,Georgeto/jmonkeyengine,amit2103/jmonkeyengine,delftsre/jmonkeyengine,shurun19851206/jMonkeyEngine,rbottema/jmonkeyengine,nickschot/jmonkeyengine,mbenson/jmonkeyengine,weilichuang/jmonkeyengine,g-rocket/jmonkeyengine,d235j/jmonkeyengine,davidB/jmonkeyengine,d235j/jmonkeyengine,OpenGrabeso/jmonkeyengine,mbenson/jmonkeyengine,OpenGrabeso/jmonkeyengine,tr0k/jmonkeyengine,InShadow/jmonkeyengine,mbenson/jmonkeyengine,OpenGrabeso/jmonkeyengine,OpenGrabeso/jmonkeyengine,olafmaas/jmonkeyengine,aaronang/jmonkeyengine,nickschot/jmonkeyengine,wrvangeest/jmonkeyengine,atomixnmc/jmonkeyengine,zzuegg/jmonkeyengine,bertleft/jmonkeyengine,zzuegg/jmonkeyengine,olafmaas/jmonkeyengine,sandervdo/jmonkeyengine,weilichuang/jmonkeyengine,danteinforno/jmonkeyengine,rbottema/jmonkeyengine,aaronang/jmonkeyengine,GreenCubes/jmonkeyengine,amit2103/jmonkeyengine,bertleft/jmonkeyengine,jMonkeyEngine/jmonkeyengine,bertleft/jmonkeyengine,shurun19851206/jMonkeyEngine,davidB/jmonkeyengine,tr0k/jmonkeyengine,d235j/jmonkeyengine,sandervdo/jmonkeyengine,g-rocket/jmonkeyengine,delftsre/jmonkeyengine,jMonkeyEngine/jmonkeyengine,d235j/jmonkeyengine,delftsre/jmonkeyengine,InShadow/jmonkeyengine,OpenGrabeso/jmonkeyengine,aaronang/jmonkeyengine,phr00t/jmonkeyengine,danteinforno/jmonkeyengine,yetanotherindie/jMonkey-Engine,zzuegg/jmonkeyengine,d235j/jmonkeyengine,skapi1992/jmonkeyengine,InShadow/jmonkeyengine,Georgeto/jmonkeyengine,mbenson/jmonkeyengine,g-rocket/jmonkeyengine,rbottema/jmonkeyengine,zzuegg/jmonkeyengine,bsmr-java/jmonkeyengine,phr00t/jmonkeyengine
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.terrain.geomipmap; import com.jme3.bounding.BoundingBox; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.material.Material; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import com.jme3.scene.control.UpdateControl; import com.jme3.terrain.Terrain; import com.jme3.terrain.geomipmap.lodcalc.LodCalculator; import com.jme3.terrain.heightmap.HeightMap; import com.jme3.terrain.heightmap.HeightMapGrid; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; /** * TerrainGrid itself is an actual TerrainQuad. Its four children are the visible four tiles. * * The grid is indexed by cells. Each cell has an integer XZ coordinate originating at 0,0. * TerrainGrid will piggyback on the TerrainLodControl so it can use the camera for its * updates as well. It does this in the overwritten update() method. * * It uses an LRU (Least Recently Used) cache of 16 terrain tiles (full TerrainQuadTrees). The * center 4 are the ones that are visible. As the camera moves, it checks what camera cell it is in * and will attach the now visible tiles. * * The 'quadIndex' variable is a 4x4 array that represents the tiles. The center * four (index numbers: 5, 6, 9, 10) are what is visible. Each quadIndex value is an * offset vector. The vector contains whole numbers and represents how many tiles in offset * this location is from the center of the map. So for example the index 11 [Vector3f(2, 0, 1)] * is located 2*terrainSize in X axis and 1*terrainSize in Z axis. * * As the camera moves, it tests what cameraCell it is in. Each camera cell covers four quad tiles * and is half way inside each one. * * +-------+-------+ * | 1 | 4 | Four terrainQuads that make up the grid * | *..|..* | with the cameraCell in the middle, covering * |----|--|--|----| all four quads. * | *..|..* | * | 2 | 3 | * +-------+-------+ * * This results in the effect of when the camera gets half way across one of the sides of a quad to * an empty (non-loaded) area, it will trigger the system to load in the next tiles. * * The tile loading is done on a background thread, and once the tile is loaded, then it is * attached to the qrid quad tree, back on the OGL thread. It will grab the terrain quad from * the LRU cache if it exists. If it does not exist, it will load in the new TerrainQuad tile. * * The loading of new tiles triggers events for any TerrainGridListeners. The events are: * -tile Attached * -tile Detached * -grid moved. * * These allow physics to update, and other operation (often needed for loading the terrain) to occur * at the right time. * * @author Anthyon */ public class TerrainGrid extends TerrainQuad { protected static final Logger log = Logger.getLogger(TerrainGrid.class.getCanonicalName()); protected Vector3f currentCamCell = Vector3f.ZERO; protected int quarterSize; // half of quadSize protected int quadSize; protected HeightMapGrid heightMapGrid; private TerrainGridTileLoader gridTileLoader; protected Vector3f[] quadIndex; protected Set<TerrainGridListener> listeners = new HashSet<TerrainGridListener>(); protected Material material; protected LRUCache<Vector3f, TerrainQuad> cache = new LRUCache<Vector3f, TerrainQuad>(16); private int cellsLoaded = 0; private int[] gridOffset; private boolean runOnce = false; protected class UpdateQuadCache implements Runnable { protected final Vector3f location; public UpdateQuadCache(Vector3f location) { this.location = location; } /** * This is executed if the camera has moved into a new CameraCell and will load in * the new TerrainQuad tiles to be children of this TerrainGrid parent. * It will first check the LRU cache to see if the terrain tile is already there, * if it is not there, it will load it in and then cache that tile. * The terrain tiles get added to the quad tree back on the OGL thread using the * attachQuadAt() method. It also resets any cached values in TerrainQuad (such as * neighbours). */ public void run() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int quadIdx = i * 4 + j; final Vector3f quadCell = location.add(quadIndex[quadIdx]); TerrainQuad q = cache.get(quadCell); if (q == null) { if (heightMapGrid != null) { // create the new Quad since it doesn't exist HeightMap heightMapAt = heightMapGrid.getHeightMapAt(quadCell); q = new TerrainQuad(getName() + "Quad" + quadCell, patchSize, quadSize, heightMapAt == null ? null : heightMapAt.getHeightMap()); q.setMaterial(material.clone()); log.log(Level.FINE, "Loaded TerrainQuad {0} from HeightMapGrid", q.getName()); } else if (gridTileLoader != null) { q = gridTileLoader.getTerrainQuadAt(quadCell); // only clone the material to the quad if it doesn't have a material of its own if(q.getMaterial()==null) q.setMaterial(material.clone()); log.log(Level.FINE, "Loaded TerrainQuad {0} from TerrainQuadGrid", q.getName()); } } cache.put(quadCell, q); if (isCenter(quadIdx)) { // if it should be attached as a child right now, attach it final int quadrant = getQuadrant(quadIdx); final TerrainQuad newQuad = q; // back on the OpenGL thread: getControl(UpdateControl.class).enqueue(new Callable() { public Object call() throws Exception { attachQuadAt(newQuad, quadrant, quadCell); //newQuad.resetCachedNeighbours(); return null; } }); } } } } } protected boolean isCenter(int quadIndex) { return quadIndex == 9 || quadIndex == 5 || quadIndex == 10 || quadIndex == 6; } protected int getQuadrant(int quadIndex) { if (quadIndex == 5) { return 1; } else if (quadIndex == 9) { return 2; } else if (quadIndex == 6) { return 3; } else if (quadIndex == 10) { return 4; } return 0; // error } public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, TerrainGridTileLoader terrainQuadGrid, Vector2f offset, float offsetAmount) { this.name = name; this.patchSize = patchSize; this.size = maxVisibleSize; this.stepScale = scale; this.offset = offset; this.offsetAmount = offsetAmount; initData(); this.gridTileLoader = terrainQuadGrid; terrainQuadGrid.setPatchSize(this.patchSize); terrainQuadGrid.setQuadSize(this.quadSize); addControl(new UpdateControl()); } public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, TerrainGridTileLoader terrainQuadGrid) { this(name, patchSize, maxVisibleSize, scale, terrainQuadGrid, new Vector2f(), 0); } public TerrainGrid(String name, int patchSize, int maxVisibleSize, TerrainGridTileLoader terrainQuadGrid) { this(name, patchSize, maxVisibleSize, Vector3f.UNIT_XYZ, terrainQuadGrid); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, HeightMapGrid heightMapGrid, Vector2f offset, float offsetAmount) { this.name = name; this.patchSize = patchSize; this.size = maxVisibleSize; this.stepScale = scale; this.offset = offset; this.offsetAmount = offsetAmount; initData(); this.heightMapGrid = heightMapGrid; heightMapGrid.setSize(this.quadSize); addControl(new UpdateControl()); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, HeightMapGrid heightMapGrid) { this(name, patchSize, maxVisibleSize, scale, heightMapGrid, new Vector2f(), 0); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, HeightMapGrid heightMapGrid) { this(name, patchSize, maxVisibleSize, Vector3f.UNIT_XYZ, heightMapGrid); } public TerrainGrid() { } private void initData() { int maxVisibleSize = size; this.quarterSize = maxVisibleSize >> 2; this.quadSize = (maxVisibleSize + 1) >> 1; this.totalSize = maxVisibleSize; this.gridOffset = new int[]{0, 0}; /* * -z * | * 1|3 * -x ----+---- x * 2|4 * | * z */ this.quadIndex = new Vector3f[]{ new Vector3f(-1, 0, -1), new Vector3f(0, 0, -1), new Vector3f(1, 0, -1), new Vector3f(2, 0, -1), new Vector3f(-1, 0, 0), new Vector3f(0, 0, 0), new Vector3f(1, 0, 0), new Vector3f(2, 0, 0), new Vector3f(-1, 0, 1), new Vector3f(0, 0, 1), new Vector3f(1, 0, 1), new Vector3f(2, 0, 1), new Vector3f(-1, 0, 2), new Vector3f(0, 0, 2), new Vector3f(1, 0, 2), new Vector3f(2, 0, 2)}; } /** * @deprecated not needed to be called any more, handled automatically */ public void initialize(Vector3f location) { if (this.material == null) { throw new RuntimeException("Material must be set prior to call of initialize"); } Vector3f camCell = this.getCamCell(location); this.updateChildren(camCell); for (TerrainGridListener l : this.listeners) { l.gridMoved(camCell); } } @Override public void update(List<Vector3f> locations, LodCalculator lodCalculator) { // for now, only the first camera is handled. // to accept more, there are two ways: // 1: every camera has an associated grid, then the location is not enough to identify which camera location has changed // 2: grids are associated with locations, and no incremental update is done, we load new grids for new locations, and unload those that are not needed anymore Vector3f cam = locations.isEmpty() ? Vector3f.ZERO.clone() : locations.get(0); Vector3f camCell = this.getCamCell(cam); // get the grid index value of where the camera is (ie. 2,1) if (cellsLoaded > 1) { // Check if cells are updated before updating gridoffset. gridOffset[0] = Math.round(camCell.x * (size / 2)); gridOffset[1] = Math.round(camCell.z * (size / 2)); cellsLoaded = 0; } if (camCell.x != this.currentCamCell.x || camCell.z != currentCamCell.z || !runOnce) { // if the camera has moved into a new cell, load new terrain into the visible 4 center quads this.updateChildren(camCell); for (TerrainGridListener l : this.listeners) { l.gridMoved(camCell); } } runOnce = true; super.update(locations, lodCalculator); } public Vector3f getCamCell(Vector3f location) { Vector3f tile = getTileCell(location); Vector3f offsetHalf = new Vector3f(-0.5f, 0, -0.5f); Vector3f shifted = tile.subtract(offsetHalf); return new Vector3f(FastMath.floor(shifted.x), 0, FastMath.floor(shifted.z)); } /** * Centered at 0,0. * Get the tile index location in integer form: * @param location world coordinate */ public Vector3f getTileCell(Vector3f location) { Vector3f tileLoc = location.divide(this.getWorldScale().mult(this.quadSize)); return tileLoc; } public TerrainGridTileLoader getGridTileLoader() { return gridTileLoader; } protected void removeQuad(int idx) { if (this.getQuad(idx) != null) { for (TerrainGridListener l : listeners) { l.tileDetached(getTileCell(this.getQuad(idx).getWorldTranslation()), this.getQuad(idx)); } this.detachChild(this.getQuad(idx)); cellsLoaded++; // For gridoffset calc., maybe the run() method is a better location for this. } } /** * Runs on the rendering thread */ protected void attachQuadAt(TerrainQuad q, int quadrant, Vector3f quadCell) { this.removeQuad(quadrant); q.setQuadrant((short) quadrant); this.attachChild(q); Vector3f loc = quadCell.mult(this.quadSize - 1).subtract(quarterSize, 0, quarterSize);// quadrant location handled TerrainQuad automatically now q.setLocalTranslation(loc); for (TerrainGridListener l : listeners) { l.tileAttached(quadCell, q); } updateModelBound(); for (Spatial s : getChildren()) { if (s instanceof TerrainQuad) { TerrainQuad tq = (TerrainQuad)s; tq.resetCachedNeighbours(); tq.fixNormalEdges(new BoundingBox(tq.getWorldTranslation(), totalSize*2, Float.MAX_VALUE, totalSize*2)); } } } @Deprecated /** * @Deprecated, use updateChildren */ protected void updateChildrens(Vector3f camCell) { updateChildren(camCell); } /** * Called when the camera has moved into a new cell. We need to * update what quads are in the scene now. * * Step 1: touch cache * LRU cache is used, so elements that need to remain * should be touched. * * Step 2: load new quads in background thread * if the camera has moved into a new cell, we load in new quads * @param camCell the cell the camera is in */ protected void updateChildren(Vector3f camCell) { int dx = 0; int dy = 0; if (currentCamCell != null) { dx = (int) (camCell.x - currentCamCell.x); dy = (int) (camCell.z - currentCamCell.z); } int xMin = 0; int xMax = 4; int yMin = 0; int yMax = 4; if (dx == -1) { // camera moved to -X direction xMax = 3; } else if (dx == 1) { // camera moved to +X direction xMin = 1; } if (dy == -1) { // camera moved to -Y direction yMax = 3; } else if (dy == 1) { // camera moved to +Y direction yMin = 1; } // Touch the items in the cache that we are and will be interested in. // We activate cells in the direction we are moving. If we didn't move // either way in one of the axes (say X or Y axis) then they are all touched. for (int i = yMin; i < yMax; i++) { for (int j = xMin; j < xMax; j++) { cache.get(camCell.add(quadIndex[i * 4 + j])); } } // --------------------------------------------------- // --------------------------------------------------- if (executor == null) { // use the same executor as the LODControl executor = createExecutorService(); } executor.submit(new UpdateQuadCache(camCell)); this.currentCamCell = camCell; } public void addListener(TerrainGridListener listener) { this.listeners.add(listener); } public Vector3f getCurrentCell() { return this.currentCamCell; } public void removeListener(TerrainGridListener listener) { this.listeners.remove(listener); } @Override public void setMaterial(Material mat) { this.material = mat; super.setMaterial(mat); } public void setQuadSize(int quadSize) { this.quadSize = quadSize; } @Override public void adjustHeight(List<Vector2f> xz, List<Float> height) { Vector3f currentGridLocation = getCurrentCell().mult(getLocalScale()).multLocal(quadSize - 1); for (Vector2f vect : xz) { vect.x -= currentGridLocation.x; vect.y -= currentGridLocation.z; } super.adjustHeight(xz, height); } @Override protected float getHeightmapHeight(int x, int z) { return super.getHeightmapHeight(x - gridOffset[0], z - gridOffset[1]); } @Override public int getNumMajorSubdivisions() { return 2; } @Override public Material getMaterial(Vector3f worldLocation) { if (worldLocation == null) return null; Vector3f tileCell = getTileCell(worldLocation); Terrain terrain = cache.get(tileCell); if (terrain == null) return null; // terrain not loaded for that cell yet! return terrain.getMaterial(worldLocation); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule c = im.getCapsule(this); name = c.readString("name", null); size = c.readInt("size", 0); patchSize = c.readInt("patchSize", 0); stepScale = (Vector3f) c.readSavable("stepScale", null); offset = (Vector2f) c.readSavable("offset", null); offsetAmount = c.readFloat("offsetAmount", 0); gridTileLoader = (TerrainGridTileLoader) c.readSavable("terrainQuadGrid", null); material = (Material) c.readSavable("material", null); initData(); if (gridTileLoader != null) { gridTileLoader.setPatchSize(this.patchSize); gridTileLoader.setQuadSize(this.quadSize); } } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule c = ex.getCapsule(this); c.write(gridTileLoader, "terrainQuadGrid", null); c.write(size, "size", 0); c.write(patchSize, "patchSize", 0); c.write(stepScale, "stepScale", null); c.write(offset, "offset", null); c.write(offsetAmount, "offsetAmount", 0); c.write(material, "material", null); } }
engine/src/terrain/com/jme3/terrain/geomipmap/TerrainGrid.java
/* * Copyright (c) 2009-2010 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.terrain.geomipmap; import com.jme3.bounding.BoundingBox; import com.jme3.export.InputCapsule; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.export.OutputCapsule; import com.jme3.material.Material; import com.jme3.math.FastMath; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import com.jme3.scene.control.UpdateControl; import com.jme3.terrain.Terrain; import com.jme3.terrain.geomipmap.lodcalc.LodCalculator; import com.jme3.terrain.heightmap.HeightMap; import com.jme3.terrain.heightmap.HeightMapGrid; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; /** * TerrainGrid itself is an actual TerrainQuad. Its four children are the visible four tiles. * * The grid is indexed by cells. Each cell has an integer XZ coordinate originating at 0,0. * TerrainGrid will piggyback on the TerrainLodControl so it can use the camera for its * updates as well. It does this in the overwritten update() method. * * It uses an LRU (Least Recently Used) cache of 16 terrain tiles (full TerrainQuadTrees). The * center 4 are the ones that are visible. As the camera moves, it checks what camera cell it is in * and will attach the now visible tiles. * * The 'quadIndex' variable is a 4x4 array that represents the tiles. The center * four (index numbers: 5, 6, 9, 10) are what is visible. Each quadIndex value is an * offset vector. The vector contains whole numbers and represents how many tiles in offset * this location is from the center of the map. So for example the index 11 [Vector3f(2, 0, 1)] * is located 2*terrainSize in X axis and 1*terrainSize in Z axis. * * As the camera moves, it tests what cameraCell it is in. Each camera cell covers four quad tiles * and is half way inside each one. * * +-------+-------+ * | 1 | 4 | Four terrainQuads that make up the grid * | *..|..* | with the cameraCell in the middle, covering * |----|--|--|----| all four quads. * | *..|..* | * | 2 | 3 | * +-------+-------+ * * This results in the effect of when the camera gets half way across one of the sides of a quad to * an empty (non-loaded) area, it will trigger the system to load in the next tiles. * * The tile loading is done on a background thread, and once the tile is loaded, then it is * attached to the qrid quad tree, back on the OGL thread. It will grab the terrain quad from * the LRU cache if it exists. If it does not exist, it will load in the new TerrainQuad tile. * * The loading of new tiles triggers events for any TerrainGridListeners. The events are: * -tile Attached * -tile Detached * -grid moved. * * These allow physics to update, and other operation (often needed for loading the terrain) to occur * at the right time. * * @author Anthyon */ public class TerrainGrid extends TerrainQuad { protected static final Logger log = Logger.getLogger(TerrainGrid.class.getCanonicalName()); protected Vector3f currentCamCell = Vector3f.ZERO; protected int quarterSize; // half of quadSize protected int quadSize; protected HeightMapGrid heightMapGrid; private TerrainGridTileLoader gridTileLoader; protected Vector3f[] quadIndex; protected Set<TerrainGridListener> listeners = new HashSet<TerrainGridListener>(); protected Material material; protected LRUCache<Vector3f, TerrainQuad> cache = new LRUCache<Vector3f, TerrainQuad>(16); private int cellsLoaded = 0; private int[] gridOffset; private boolean runOnce = false; protected class UpdateQuadCache implements Runnable { protected final Vector3f location; public UpdateQuadCache(Vector3f location) { this.location = location; } /** * This is executed if the camera has moved into a new CameraCell and will load in * the new TerrainQuad tiles to be children of this TerrainGrid parent. * It will first check the LRU cache to see if the terrain tile is already there, * if it is not there, it will load it in and then cache that tile. * The terrain tiles get added to the quad tree back on the OGL thread using the * attachQuadAt() method. It also resets any cached values in TerrainQuad (such as * neighbours). */ public void run() { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { int quadIdx = i * 4 + j; final Vector3f quadCell = location.add(quadIndex[quadIdx]); TerrainQuad q = cache.get(quadCell); if (q == null) { if (heightMapGrid != null) { // create the new Quad since it doesn't exist HeightMap heightMapAt = heightMapGrid.getHeightMapAt(quadCell); q = new TerrainQuad(getName() + "Quad" + quadCell, patchSize, quadSize, heightMapAt == null ? null : heightMapAt.getHeightMap()); q.setMaterial(material.clone()); log.log(Level.FINE, "Loaded TerrainQuad {0} from HeightMapGrid", q.getName()); } else if (gridTileLoader != null) { q = gridTileLoader.getTerrainQuadAt(quadCell); q.setMaterial(material.clone()); log.log(Level.FINE, "Loaded TerrainQuad {0} from TerrainQuadGrid", q.getName()); } } cache.put(quadCell, q); if (isCenter(quadIdx)) { // if it should be attached as a child right now, attach it final int quadrant = getQuadrant(quadIdx); final TerrainQuad newQuad = q; // back on the OpenGL thread: getControl(UpdateControl.class).enqueue(new Callable() { public Object call() throws Exception { attachQuadAt(newQuad, quadrant, quadCell); //newQuad.resetCachedNeighbours(); return null; } }); } } } } } protected boolean isCenter(int quadIndex) { return quadIndex == 9 || quadIndex == 5 || quadIndex == 10 || quadIndex == 6; } protected int getQuadrant(int quadIndex) { if (quadIndex == 5) { return 1; } else if (quadIndex == 9) { return 2; } else if (quadIndex == 6) { return 3; } else if (quadIndex == 10) { return 4; } return 0; // error } public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, TerrainGridTileLoader terrainQuadGrid, Vector2f offset, float offsetAmount) { this.name = name; this.patchSize = patchSize; this.size = maxVisibleSize; this.stepScale = scale; this.offset = offset; this.offsetAmount = offsetAmount; initData(); this.gridTileLoader = terrainQuadGrid; terrainQuadGrid.setPatchSize(this.patchSize); terrainQuadGrid.setQuadSize(this.quadSize); addControl(new UpdateControl()); } public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, TerrainGridTileLoader terrainQuadGrid) { this(name, patchSize, maxVisibleSize, scale, terrainQuadGrid, new Vector2f(), 0); } public TerrainGrid(String name, int patchSize, int maxVisibleSize, TerrainGridTileLoader terrainQuadGrid) { this(name, patchSize, maxVisibleSize, Vector3f.UNIT_XYZ, terrainQuadGrid); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, HeightMapGrid heightMapGrid, Vector2f offset, float offsetAmount) { this.name = name; this.patchSize = patchSize; this.size = maxVisibleSize; this.stepScale = scale; this.offset = offset; this.offsetAmount = offsetAmount; initData(); this.heightMapGrid = heightMapGrid; heightMapGrid.setSize(this.quadSize); addControl(new UpdateControl()); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, Vector3f scale, HeightMapGrid heightMapGrid) { this(name, patchSize, maxVisibleSize, scale, heightMapGrid, new Vector2f(), 0); } @Deprecated public TerrainGrid(String name, int patchSize, int maxVisibleSize, HeightMapGrid heightMapGrid) { this(name, patchSize, maxVisibleSize, Vector3f.UNIT_XYZ, heightMapGrid); } public TerrainGrid() { } private void initData() { int maxVisibleSize = size; this.quarterSize = maxVisibleSize >> 2; this.quadSize = (maxVisibleSize + 1) >> 1; this.totalSize = maxVisibleSize; this.gridOffset = new int[]{0, 0}; /* * -z * | * 1|3 * -x ----+---- x * 2|4 * | * z */ this.quadIndex = new Vector3f[]{ new Vector3f(-1, 0, -1), new Vector3f(0, 0, -1), new Vector3f(1, 0, -1), new Vector3f(2, 0, -1), new Vector3f(-1, 0, 0), new Vector3f(0, 0, 0), new Vector3f(1, 0, 0), new Vector3f(2, 0, 0), new Vector3f(-1, 0, 1), new Vector3f(0, 0, 1), new Vector3f(1, 0, 1), new Vector3f(2, 0, 1), new Vector3f(-1, 0, 2), new Vector3f(0, 0, 2), new Vector3f(1, 0, 2), new Vector3f(2, 0, 2)}; } /** * @deprecated not needed to be called any more, handled automatically */ public void initialize(Vector3f location) { if (this.material == null) { throw new RuntimeException("Material must be set prior to call of initialize"); } Vector3f camCell = this.getCamCell(location); this.updateChildren(camCell); for (TerrainGridListener l : this.listeners) { l.gridMoved(camCell); } } @Override public void update(List<Vector3f> locations, LodCalculator lodCalculator) { // for now, only the first camera is handled. // to accept more, there are two ways: // 1: every camera has an associated grid, then the location is not enough to identify which camera location has changed // 2: grids are associated with locations, and no incremental update is done, we load new grids for new locations, and unload those that are not needed anymore Vector3f cam = locations.isEmpty() ? Vector3f.ZERO.clone() : locations.get(0); Vector3f camCell = this.getCamCell(cam); // get the grid index value of where the camera is (ie. 2,1) if (cellsLoaded > 1) { // Check if cells are updated before updating gridoffset. gridOffset[0] = Math.round(camCell.x * (size / 2)); gridOffset[1] = Math.round(camCell.z * (size / 2)); cellsLoaded = 0; } if (camCell.x != this.currentCamCell.x || camCell.z != currentCamCell.z || !runOnce) { // if the camera has moved into a new cell, load new terrain into the visible 4 center quads this.updateChildren(camCell); for (TerrainGridListener l : this.listeners) { l.gridMoved(camCell); } } runOnce = true; super.update(locations, lodCalculator); } public Vector3f getCamCell(Vector3f location) { Vector3f tile = getTileCell(location); Vector3f offsetHalf = new Vector3f(-0.5f, 0, -0.5f); Vector3f shifted = tile.subtract(offsetHalf); return new Vector3f(FastMath.floor(shifted.x), 0, FastMath.floor(shifted.z)); } /** * Centered at 0,0. * Get the tile index location in integer form: * @param location world coordinate */ public Vector3f getTileCell(Vector3f location) { Vector3f tileLoc = location.divide(this.getWorldScale().mult(this.quadSize)); return tileLoc; } public TerrainGridTileLoader getGridTileLoader() { return gridTileLoader; } protected void removeQuad(int idx) { if (this.getQuad(idx) != null) { for (TerrainGridListener l : listeners) { l.tileDetached(getTileCell(this.getQuad(idx).getWorldTranslation()), this.getQuad(idx)); } this.detachChild(this.getQuad(idx)); cellsLoaded++; // For gridoffset calc., maybe the run() method is a better location for this. } } /** * Runs on the rendering thread */ protected void attachQuadAt(TerrainQuad q, int quadrant, Vector3f quadCell) { this.removeQuad(quadrant); q.setQuadrant((short) quadrant); this.attachChild(q); Vector3f loc = quadCell.mult(this.quadSize - 1).subtract(quarterSize, 0, quarterSize);// quadrant location handled TerrainQuad automatically now q.setLocalTranslation(loc); for (TerrainGridListener l : listeners) { l.tileAttached(quadCell, q); } updateModelBound(); for (Spatial s : getChildren()) { if (s instanceof TerrainQuad) { TerrainQuad tq = (TerrainQuad)s; tq.resetCachedNeighbours(); tq.fixNormalEdges(new BoundingBox(tq.getWorldTranslation(), totalSize*2, Float.MAX_VALUE, totalSize*2)); } } } @Deprecated /** * @Deprecated, use updateChildren */ protected void updateChildrens(Vector3f camCell) { updateChildren(camCell); } /** * Called when the camera has moved into a new cell. We need to * update what quads are in the scene now. * * Step 1: touch cache * LRU cache is used, so elements that need to remain * should be touched. * * Step 2: load new quads in background thread * if the camera has moved into a new cell, we load in new quads * @param camCell the cell the camera is in */ protected void updateChildren(Vector3f camCell) { int dx = 0; int dy = 0; if (currentCamCell != null) { dx = (int) (camCell.x - currentCamCell.x); dy = (int) (camCell.z - currentCamCell.z); } int xMin = 0; int xMax = 4; int yMin = 0; int yMax = 4; if (dx == -1) { // camera moved to -X direction xMax = 3; } else if (dx == 1) { // camera moved to +X direction xMin = 1; } if (dy == -1) { // camera moved to -Y direction yMax = 3; } else if (dy == 1) { // camera moved to +Y direction yMin = 1; } // Touch the items in the cache that we are and will be interested in. // We activate cells in the direction we are moving. If we didn't move // either way in one of the axes (say X or Y axis) then they are all touched. for (int i = yMin; i < yMax; i++) { for (int j = xMin; j < xMax; j++) { cache.get(camCell.add(quadIndex[i * 4 + j])); } } // --------------------------------------------------- // --------------------------------------------------- if (executor == null) { // use the same executor as the LODControl executor = createExecutorService(); } executor.submit(new UpdateQuadCache(camCell)); this.currentCamCell = camCell; } public void addListener(TerrainGridListener listener) { this.listeners.add(listener); } public Vector3f getCurrentCell() { return this.currentCamCell; } public void removeListener(TerrainGridListener listener) { this.listeners.remove(listener); } @Override public void setMaterial(Material mat) { this.material = mat; super.setMaterial(mat); } public void setQuadSize(int quadSize) { this.quadSize = quadSize; } @Override public void adjustHeight(List<Vector2f> xz, List<Float> height) { Vector3f currentGridLocation = getCurrentCell().mult(getLocalScale()).multLocal(quadSize - 1); for (Vector2f vect : xz) { vect.x -= currentGridLocation.x; vect.y -= currentGridLocation.z; } super.adjustHeight(xz, height); } @Override protected float getHeightmapHeight(int x, int z) { return super.getHeightmapHeight(x - gridOffset[0], z - gridOffset[1]); } @Override public int getNumMajorSubdivisions() { return 2; } @Override public Material getMaterial(Vector3f worldLocation) { if (worldLocation == null) return null; Vector3f tileCell = getTileCell(worldLocation); Terrain terrain = cache.get(tileCell); if (terrain == null) return null; // terrain not loaded for that cell yet! return terrain.getMaterial(worldLocation); } @Override public void read(JmeImporter im) throws IOException { super.read(im); InputCapsule c = im.getCapsule(this); name = c.readString("name", null); size = c.readInt("size", 0); patchSize = c.readInt("patchSize", 0); stepScale = (Vector3f) c.readSavable("stepScale", null); offset = (Vector2f) c.readSavable("offset", null); offsetAmount = c.readFloat("offsetAmount", 0); gridTileLoader = (TerrainGridTileLoader) c.readSavable("terrainQuadGrid", null); material = (Material) c.readSavable("material", null); initData(); if (gridTileLoader != null) { gridTileLoader.setPatchSize(this.patchSize); gridTileLoader.setQuadSize(this.quadSize); } } @Override public void write(JmeExporter ex) throws IOException { super.write(ex); OutputCapsule c = ex.getCapsule(this); c.write(gridTileLoader, "terrainQuadGrid", null); c.write(size, "size", 0); c.write(patchSize, "patchSize", 0); c.write(stepScale, "stepScale", null); c.write(offset, "offset", null); c.write(offsetAmount, "offsetAmount", 0); c.write(material, "material", null); } }
Fix to TerrainGrid: only clone the grid's material to child quad if it doesn't have a material of its own git-svn-id: f9411aee4f13664f2fc428a5b3e824fe43a079a3@8970 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/terrain/com/jme3/terrain/geomipmap/TerrainGrid.java
Fix to TerrainGrid: only clone the grid's material to child quad if it doesn't have a material of its own
<ide><path>ngine/src/terrain/com/jme3/terrain/geomipmap/TerrainGrid.java <ide> log.log(Level.FINE, "Loaded TerrainQuad {0} from HeightMapGrid", q.getName()); <ide> } else if (gridTileLoader != null) { <ide> q = gridTileLoader.getTerrainQuadAt(quadCell); <del> q.setMaterial(material.clone()); <add> // only clone the material to the quad if it doesn't have a material of its own <add> if(q.getMaterial()==null) q.setMaterial(material.clone()); <ide> log.log(Level.FINE, "Loaded TerrainQuad {0} from TerrainQuadGrid", q.getName()); <ide> } <ide> }
JavaScript
mit
5c24cef3aa918d1fbf4069527b71e5a477dd9f05
0
ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend,ForestGuardian/ForestGuardianBackend
/** * Created by Luis Alonso Murillo Rojas on 11/12/16. */ /* Global definitions */ var map; var route; var fireStationMarker; var currentFireCoordinates; var gpsMarker; var reportMarker; var MODISLayer; var fireIcon; var fireStationIcon; var markerIcon; var markerArea; var reportMarkerLocation = { 'latitude':0.0, 'longitude':0.0 } var currentLocation = { 'latitude':10.07568504578726, 'longitude': -84.31182861328125 } var layerCollection ={ forest: [], fires: [], weather: [], protected_areas: [] } var windytyInit = { // Required: API key key: 'pBEnvSWfnXaWpNC', // Optional: Initial state of the map lat: 10.07568504578726, lon: -84.31182861328125, zoom: 8, } /* Interface function with the client app */ //@function displayWildfiresDetails //Funtion that parse the MODIS data an send it to the corresponding mobile clients //@param {double} lat (latitude) of the fire point //@param {double} lng (longitude) of the fire point //@param {double} birghtness value of the fire point //@param {double} scan value //@param {double} track value //@param {String} adquisitionTime from the satellite //@param {String} satellite identification //@param {integer} confidence value //@param {String} version of the data //@param {double} bright_t31 value //@param {double} frp value //@param {String} daynight value function displayWildfiresDetails(lat, lng, brightness, scan, track, adquisitionTime, satellite, confidence, version, bright_t31, frp, daynight) { var jsonMODIS = {"LATITUDE":lat, "LONGITUDE":lng, "BRIGHTNESS":brightness, "SCAN":scan, "TRACK":track, "ADQUISITION_TIME":adquisitionTime, "SATELLITE":satellite, "CONFIDENCE":confidence, "VERSION":version, "BRIGHT_T31":bright_t31, "FRP":frp, "DAYNIGHT":daynight}; try { mobile.getMODISData(JSON.stringify(jsonMODIS)); } catch(err) { console.log("Error trying to invoke mobile method"); } } //@function setUserCurrentLocation //Funtor that centers the map to the current a given point provided by the clients //@param {double} latitued //@param {double} longitude function setUserCurrentLocation(latitude, longitude) { // Initialize marker if null if ( gpsMarker == null ){ gpsMarker = L.marker([latitude, longitude], {icon: markerIcon}); gpsMarker.addTo(map); } currentLocation.latitude = latitude; currentLocation.longitude = longitude; try { mobile.notifyCurrentLocation(); } catch (err) { console.log("Error trying to invoke mobile method"); } } function moveToUserCurrentLocation(){ map.setView(L.latLng(currentLocation.latitude, currentLocation.longitude), 8); } //@function mobileShowDetails //Function that notify the client when is the time to show the detail information of a given fire point function mobileShowDetails() { try { mobile.showWildfireDetails(); } catch(err) { console.log("Error trying to invoke mobile method"); } } //@function setRouteFromTwoPoints //Function that sets the route from a point A to a point B //@param {double} latitudeA of the point A //@param {double} longitudeA of the point A //@param {double} latitudeB of the point B //@param {double} longitudeB of the point B function setRouteFromTwoPoints(latitudeA, longitudeA, latitudeB, longitudeB) { route.setWaypoints([ L.latLng(latitudeA, longitudeA), L.latLng(latitudeB, longitudeB) ]); } //@function removeRoute //Function that removes the route from the map function removeRoute() { route.setWaypoints([]); } function addReportLocation(){ var center = map.getBounds().getCenter(); var latitude = center.lat; var longitude = center.lng; // Initialize marker if null if ( reportMarker === null || reportMarker === undefined ) { reportMarker = L.marker([latitude, longitude], {icon: markerArea, draggable: 'true'}); reportMarker.addTo(map); reportMarker.on("dragend",function(ev){ var position = ev.target.getLatLng(); reportMarkerLocation.latitude = position.lat; reportMarkerLocation.longitude = position.lng; console.log("latitude: " + reportMarkerLocation.latitude); console.log("longitude: " + reportMarkerLocation.longitude); }); } reportMarkerLocation.latitude = latitude; reportMarkerLocation.longitude = longitude; console.log("latitude: " + reportMarkerLocation.latitude); console.log("longitude: " + reportMarkerLocation.longitude); } function clearReportLocation(){ map.removeLayer(reportMarker); //FIXME This can be improved by setting a state variable. reportMarker = null; } function prepareReportLocation(){ console.log("prepareReportLocation"); console.log(reportMarkerLocation.latitude); console.log(reportMarkerLocation.longitude); mobile.reportLocation(reportMarkerLocation.latitude, reportMarkerLocation.longitude); } function addFireStationMark(latitude, longitude) { fireStationMarker = L.marker([latitude, longitude], {icon: fireStationIcon}); fireStationMarker.addTo(map); } function removeFireStationMark() { if (fireStationMarker == null){ return; } fireStationMarker.removeFrom(map); } /* Pop up functions */ //@function addWildfireMessage //Function that creates a popup message with some info related to the pressed fire point //@param {double} latitude //@param {double} longitude //@param {double} brightness value of the wildfire //@param {double} temperature value of the place where the fire is located //@param {double} humidity value of the place where the fire is located function addWildfireMessage(latitude, longitude, brightness, temperature, humidity) { var popup = L.popup({offset: L.point(0, -37)}) .setLatLng(L.latLng(latitude, longitude)) .setContent('<b>Incendio</b>' + '<br>Intensidad: ' + brightness + " K" + '<br>Temperatura: ' + temperature + " &#8451;" + '<br>Humedad: ' + humidity + "%" + '<br><a href="javascript:mobileShowDetails();">Detalles</a>') .openOn(map); } function removeWildfireMessage() { map.closePopup(); } //Callback that will the called each time a fire marker is creator on the map. //@param {Object} feature //@param {Layer} layer where the marker are been displayed function onEachFeature(feature, layer) { layer.setIcon(fireIcon); /* onClick event */ layer.on('click', function (e) { displayWildfiresDetails(e.latlng.lat, e.latlng.lng, e.target.feature.properties.brightness, e.target.feature.properties.scan, e.target.feature.properties.track, e.target.feature.properties.acquisition_time, e.target.feature.properties.satellite, e.target.feature.properties.confidence, e.target.feature.properties.version, e.target.feature.properties.bright_t31, e.target.feature.properties.frp, e.target.feature.properties.daynight); }); } //@function downloadMODISData //Function that downloads the MODIS data from the backend function downloadMODISData() { console.log('downloading modis data...'); var bounds = map.getBounds(); var data = new FormData(); data.append("north", bounds.getNorth()); data.append("south", bounds.getSouth()); data.append("east", bounds.getEast()); data.append("west", bounds.getWest()); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { try { var geoJSONData = JSON.parse(this.responseText); MODISLayer.clearLayers(); MODISLayer.addData(geoJSONData); } catch (err) { console.log("Error downloading the MODIS data: " + err); } } }); xhr.open("POST", "/modis_data/fires.json"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.send(data); } /* Map events functions */ //@function checkZoomLevel //Function that check the the zoom level of the map in order to decide if display or not the datailed MODIS data function checkZoomLevel() { var zoomLevel = map.getZoom(); console.log("Zoom level: " + zoomLevel); if (zoomLevel > 7) { console.log("Download the MODIS data"); downloadMODISData(); } else { console.log("MODISLayer clear layer"); MODISLayer.clearLayers(); } } //region Map Components Initialization function loadForestLayerIfEmpty(){ if ( $.isEmptyObject(layerCollection.forest) ) { /* Forest types for Costa Rica */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi18_tipos_bosque_costa_rica_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for Honduras */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi21_tipos_bosque_honduras_2015_v2@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for El Salvador */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi19_tipos_bosque_el_salvador_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for Belice */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi15_tipos_bosque_belice_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); } } function loadWindsLayerIfEmpty(){ //Do Nothing } function loadFiresLayerIfEmpty(){ //NASA's WMS service if ( $.isEmptyObject(layerCollection.fires) ) { layerCollection.fires.push( L.tileLayer.wms('https://firms.modaps.eosdis.nasa.gov/wms/c6?', { layers: 'fires24', transparent: true, format: 'image/png' }) ) } } function loadWeatherLayerIfEmpty(){ /* Central America weather perspectives */ if ( $.isEmptyObject(layerCollection.weather) ) { layerCollection.weather.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'perspectiva_ca_mjj', styles: 'perspectiva_ca_mjj', transparent: true, format: 'image/png' }) ); } } function loadProtectedAreasLayerIfEmpty(){ if ( $.isEmptyObject(layerCollection.protected_areas) ) { /* Protected areas for Costa Rica */ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi08_areas_prote_costa_rica_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Honduras*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi11_areas_prote_honduras_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for El Salvador*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi09_areas_prote_salvador_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Belice*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi07_areas_prote_belice_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Panama*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi13_areas_prote_panama_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Guatemala*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi10_areas_prote_guatemala_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Caribbean*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi01_areas_protegidas_caribe_2008', styles: 'bi01_areas_protegidas_caribe_2008', transparent: true, format: 'image/png' })); /* Protected areas for Nicaragua*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi12_areas_prote_nicaragua_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); } } function loadIcons(){ /* Fire station mark */ fireStationIcon = L.icon({ iconUrl: '/assets/firemen.png', iconSize: [32, 37], iconAnchor: [16, 36], popupAnchor: [0, -37] }); markerIcon = L.icon({ iconUrl: '/assets/marker-gps.png', iconSize: [16, 16], iconAnchor: [8, 8], popupAnchor: [0, -37] }); markerArea = L.icon({ iconUrl: '/assets/marker-area.png', iconSize: [180, 180], iconAnchor: [90, 90], popupAnchor: [0, 0] }); /* Wildfire icon */ fireIcon = L.icon({ iconUrl: '/assets/fire.png', iconSize: [35, 60], iconAnchor: [17, 30], popupAnchor: [0, -30] }); } //endregion //region Layers Toggle Display function hideForestLayer(){ layerCollection.forest.forEach( function(layer){ map.removeLayer(layer); }); } function showForestLayer(){ loadForestLayerIfEmpty(); layerCollection.forest.forEach( function(layer){ layer.addTo(map); }); } function hideWindsLayer(){ $('.leaflet-overlay-pane').hide(); $('a.logo').hide(); $('#legend').hide(); } function showWindsLayer(){ loadWindsLayerIfEmpty(); $('.leaflet-overlay-pane').show(); $('a.logo').show(); $('#legend').show(); } function hideFiresLayer(){ layerCollection.fires.forEach( function(layer){ map.removeLayer(layer); }); } function showFiresLayer() { loadFiresLayerIfEmpty(); layerCollection.fires.forEach( function(layer){ layer.addTo(map); }); } function hideWeatherLayer(){ layerCollection.weather.forEach( function(layer){ map.removeLayer(layer); }); } function showWeatherLayer(){ loadWeatherLayerIfEmpty(); layerCollection.weather.forEach( function(layer){ console.log(layer); layer.addTo(map); }); } function hideProtectedAreasLayer(){ layerCollection.protected_areas.forEach( function(layer){ map.removeLayer(layer); }); } function showProtectedAreasLayer(){ loadProtectedAreasLayerIfEmpty(); layerCollection.protected_areas.forEach( function(layer){ layer.addTo(map); }); } function initializeMapOptions(pMap, pMapView){ /* Routing */ route = L.Routing.control({ waypoints: [], routeWhileDragging: false, createMarker: function() { return null; }, router: L.Routing.mapbox('pk.eyJ1IjoibHVtdXJpbGxvIiwiYSI6IlVRTlZkbFkifQ.nFkWwVMJm_5mUy-9ye65Og') }); route.addTo(pMap); loadIcons(); //Capturing the moveend event from the map pMap.on('moveend', function() { checkZoomLevel(); }); //Data from the backend MODISLayer = new L.GeoJSON(null, { onEachFeature:onEachFeature }).addTo(pMap); showFiresLayer(); if ( pMapView.hasClass("weather_perspective") ){ showWeatherLayer(); }; if ( pMapView.hasClass("forests") ){ showForestLayer(); }; if ( pMapView.hasClass("protected_areas") ){ showProtectedAreasLayer(); }; } function isWindyMap() { return $("#windyty").length == 1; } //region UI Cleaning function hideControls(){ $('.leaflet-control-container').hide(); } function relocateWindyLogo(){ var logoView = $('a.logo'); logoView.css( { 'right': '10px', 'top': '5px', 'left': 'initial', 'bottom': 'initial' } ); } function relocateLegend(){ var legendView = $('#legend'); legendView.css( { 'right': '0px', 'top': '50px', 'left': 'initial', 'bottom': 'initial' } ); } function overrideUI(){ hideControls(); relocateWindyLogo(); relocateLegend(); } function overrideWindyMetrics(){ // Observe for changes on legend to be sure that is placed correctly // https://stackoverflow.com/questions/43622161/javascript-callback-function-when-an-elements-attributes-change var legend = document.getElementById('legend'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log("legend is changing!"); // run some change when the style is mutated overrideUI(); }); }); observer.observe(legend, { attributes: true }); // Change metric W.overlays.wind.setMetric( 'km/h' ); } function windytyMain(pMap) { map = pMap; //global ref setBaseMap(map); // overrideWindyMetrics(); initializeMapOptions(pMap, $('#windyty') ); downloadMODISData(); //ui cleaning overrideUI(); } function setBaseMap(pMap){ L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', maxZoom: 18 }).addTo(pMap); } //endregion function defaultMain(){ //Map where the data will be displayed map = L.map('map').setView([10.07568504578726, -84.31182861328125], 8); //Some setting to the general map setBaseMap(map); } $(function() { if ( !isWindyMap() ) { defaultMain(); initializeMapOptions( map, $('#map') ); downloadMODISData(); } });
app/assets/javascripts/maps.js
/** * Created by Luis Alonso Murillo Rojas on 11/12/16. */ /* Global definitions */ var map; var route; var fireStationMarker; var currentFireCoordinates; var gpsMarker; var reportMarker; var MODISLayer; var fireIcon; var fireStationIcon; var markerIcon; var markerArea; var reportMarkerLocation = { 'latitude':0.0, 'longitude':0.0 } var currentLocation = { 'latitude':10.07568504578726, 'longitude': -84.31182861328125 } var layerCollection ={ forest: [], fires: [], weather: [], protected_areas: [] } var windytyInit = { // Required: API key key: 'pBEnvSWfnXaWpNC', // Optional: Initial state of the map lat: 10.07568504578726, lon: -84.31182861328125, zoom: 8, } /* Interface function with the client app */ //@function displayWildfiresDetails //Funtion that parse the MODIS data an send it to the corresponding mobile clients //@param {double} lat (latitude) of the fire point //@param {double} lng (longitude) of the fire point //@param {double} birghtness value of the fire point //@param {double} scan value //@param {double} track value //@param {String} adquisitionTime from the satellite //@param {String} satellite identification //@param {integer} confidence value //@param {String} version of the data //@param {double} bright_t31 value //@param {double} frp value //@param {String} daynight value function displayWildfiresDetails(lat, lng, brightness, scan, track, adquisitionTime, satellite, confidence, version, bright_t31, frp, daynight) { var jsonMODIS = {"LATITUDE":lat, "LONGITUDE":lng, "BRIGHTNESS":brightness, "SCAN":scan, "TRACK":track, "ADQUISITION_TIME":adquisitionTime, "SATELLITE":satellite, "CONFIDENCE":confidence, "VERSION":version, "BRIGHT_T31":bright_t31, "FRP":frp, "DAYNIGHT":daynight}; try { mobile.getMODISData(JSON.stringify(jsonMODIS)); } catch(err) { console.log("Error trying to invoke mobile method"); } } //@function setUserCurrentLocation //Funtor that centers the map to the current a given point provided by the clients //@param {double} latitued //@param {double} longitude function setUserCurrentLocation(latitude, longitude) { // Initialize marker if null if ( gpsMarker == null ){ gpsMarker = L.marker([latitude, longitude], {icon: markerIcon}); gpsMarker.addTo(map); } currentLocation.latitude = latitude; currentLocation.longitude = longitude; try { mobile.notifyCurrentLocation(); } catch (err) { console.log("Error trying to invoke mobile method"); } } function moveToUserCurrentLocation(){ map.setView(L.latLng(currentLocation.latitude, currentLocation.longitude), 8); } //@function mobileShowDetails //Function that notify the client when is the time to show the detail information of a given fire point function mobileShowDetails() { try { mobile.showWildfireDetails(); } catch(err) { console.log("Error trying to invoke mobile method"); } } //@function setRouteFromTwoPoints //Function that sets the route from a point A to a point B //@param {double} latitudeA of the point A //@param {double} longitudeA of the point A //@param {double} latitudeB of the point B //@param {double} longitudeB of the point B function setRouteFromTwoPoints(latitudeA, longitudeA, latitudeB, longitudeB) { route.setWaypoints([ L.latLng(latitudeA, longitudeA), L.latLng(latitudeB, longitudeB) ]); } //@function removeRoute //Function that removes the route from the map function removeRoute() { route.setWaypoints([]); } function addReportLocation(){ var center = map.getBounds().getCenter(); var latitude = center.latitude; var longitude = center.longitude; // Initialize marker if null if ( reportMarker === null || reportMarker === undefined ) { reportMarker = L.marker([latitude, longitude], {icon: markerArea, draggable: 'true'}); reportMarker.addTo(map); reportMarker.on("dragend",function(ev){ var position = ev.target.getLatLng(); reportMarkerLocation.latitude = position.lat; reportMarkerLocation.longitude = position.lng; console.log("latitude: " + reportMarkerLocation.latitude); console.log("longitude: " + reportMarkerLocation.longitude); }); } reportMarkerLocation.latitude = latitude; reportMarkerLocation.longitude = longitude; console.log("latitude: " + reportMarkerLocation.latitude); console.log("longitude: " + reportMarkerLocation.longitude); } function clearReportLocation(){ map.removeLayer(reportMarker); //FIXME This can be improved by setting a state variable. reportMarker = null; } function prepareReportLocation(){ console.log("prepareReportLocation"); console.log(reportMarkerLocation.latitude); console.log(reportMarkerLocation.longitude); mobile.reportLocation(reportMarkerLocation.latitude, reportMarkerLocation.longitude); } function addFireStationMark(latitude, longitude) { fireStationMarker = L.marker([latitude, longitude], {icon: fireStationIcon}); fireStationMarker.addTo(map); } function removeFireStationMark() { if (fireStationMarker == null){ return; } fireStationMarker.removeFrom(map); } /* Pop up functions */ //@function addWildfireMessage //Function that creates a popup message with some info related to the pressed fire point //@param {double} latitude //@param {double} longitude //@param {double} brightness value of the wildfire //@param {double} temperature value of the place where the fire is located //@param {double} humidity value of the place where the fire is located function addWildfireMessage(latitude, longitude, brightness, temperature, humidity) { var popup = L.popup({offset: L.point(0, -37)}) .setLatLng(L.latLng(latitude, longitude)) .setContent('<b>Incendio</b>' + '<br>Intensidad: ' + brightness + " K" + '<br>Temperatura: ' + temperature + " &#8451;" + '<br>Humedad: ' + humidity + "%" + '<br><a href="javascript:mobileShowDetails();">Detalles</a>') .openOn(map); } function removeWildfireMessage() { map.closePopup(); } //Callback that will the called each time a fire marker is creator on the map. //@param {Object} feature //@param {Layer} layer where the marker are been displayed function onEachFeature(feature, layer) { layer.setIcon(fireIcon); /* onClick event */ layer.on('click', function (e) { displayWildfiresDetails(e.latlng.lat, e.latlng.lng, e.target.feature.properties.brightness, e.target.feature.properties.scan, e.target.feature.properties.track, e.target.feature.properties.acquisition_time, e.target.feature.properties.satellite, e.target.feature.properties.confidence, e.target.feature.properties.version, e.target.feature.properties.bright_t31, e.target.feature.properties.frp, e.target.feature.properties.daynight); }); } //@function downloadMODISData //Function that downloads the MODIS data from the backend function downloadMODISData() { console.log('downloading modis data...'); var bounds = map.getBounds(); var data = new FormData(); data.append("north", bounds.getNorth()); data.append("south", bounds.getSouth()); data.append("east", bounds.getEast()); data.append("west", bounds.getWest()); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { try { var geoJSONData = JSON.parse(this.responseText); MODISLayer.clearLayers(); MODISLayer.addData(geoJSONData); } catch (err) { console.log("Error downloading the MODIS data: " + err); } } }); xhr.open("POST", "/modis_data/fires.json"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.send(data); } /* Map events functions */ //@function checkZoomLevel //Function that check the the zoom level of the map in order to decide if display or not the datailed MODIS data function checkZoomLevel() { var zoomLevel = map.getZoom(); console.log("Zoom level: " + zoomLevel); if (zoomLevel > 7) { console.log("Download the MODIS data"); downloadMODISData(); } else { console.log("MODISLayer clear layer"); MODISLayer.clearLayers(); } } //region Map Components Initialization function loadForestLayerIfEmpty(){ if ( $.isEmptyObject(layerCollection.forest) ) { /* Forest types for Costa Rica */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi18_tipos_bosque_costa_rica_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for Honduras */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi21_tipos_bosque_honduras_2015_v2@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for El Salvador */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi19_tipos_bosque_el_salvador_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); /* Forest types for Belice */ layerCollection.forest.push(L.tileLayer('http://138.68.63.173/geoserver/gwc/service/tms/1.0.0/geonode:bi15_tipos_bosque_belice_2015@EPSG:900913@png/{z}/{x}/{y}.png', { tms: true })); } } function loadWindsLayerIfEmpty(){ //Do Nothing } function loadFiresLayerIfEmpty(){ //NASA's WMS service if ( $.isEmptyObject(layerCollection.fires) ) { layerCollection.fires.push( L.tileLayer.wms('https://firms.modaps.eosdis.nasa.gov/wms/c6?', { layers: 'fires24', transparent: true, format: 'image/png' }) ) } } function loadWeatherLayerIfEmpty(){ /* Central America weather perspectives */ if ( $.isEmptyObject(layerCollection.weather) ) { layerCollection.weather.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'perspectiva_ca_mjj', styles: 'perspectiva_ca_mjj', transparent: true, format: 'image/png' }) ); } } function loadProtectedAreasLayerIfEmpty(){ if ( $.isEmptyObject(layerCollection.protected_areas) ) { /* Protected areas for Costa Rica */ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi08_areas_prote_costa_rica_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Honduras*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi11_areas_prote_honduras_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for El Salvador*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi09_areas_prote_salvador_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Belice*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi07_areas_prote_belice_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Panama*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi13_areas_prote_panama_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Guatemala*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi10_areas_prote_guatemala_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); /* Protected areas for Caribbean*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi01_areas_protegidas_caribe_2008', styles: 'bi01_areas_protegidas_caribe_2008', transparent: true, format: 'image/png' })); /* Protected areas for Nicaragua*/ layerCollection.protected_areas.push(L.tileLayer.wms('http://138.68.63.173/geoserver/ows?', { layers: 'bi12_areas_prote_nicaragua_2014', styles: 'bi07_areas_prote_belice_2014', transparent: true, format: 'image/png' })); } } function loadIcons(){ /* Fire station mark */ fireStationIcon = L.icon({ iconUrl: '/assets/firemen.png', iconSize: [32, 37], iconAnchor: [16, 36], popupAnchor: [0, -37] }); markerIcon = L.icon({ iconUrl: '/assets/marker-gps.png', iconSize: [16, 16], iconAnchor: [8, 8], popupAnchor: [0, -37] }); markerArea = L.icon({ iconUrl: '/assets/marker-area.png', iconSize: [180, 180], iconAnchor: [90, 90], popupAnchor: [0, 0] }); /* Wildfire icon */ fireIcon = L.icon({ iconUrl: '/assets/fire.png', iconSize: [35, 60], iconAnchor: [17, 30], popupAnchor: [0, -30] }); } //endregion //region Layers Toggle Display function hideForestLayer(){ layerCollection.forest.forEach( function(layer){ map.removeLayer(layer); }); } function showForestLayer(){ loadForestLayerIfEmpty(); layerCollection.forest.forEach( function(layer){ layer.addTo(map); }); } function hideWindsLayer(){ $('.leaflet-overlay-pane').hide(); $('a.logo').hide(); $('#legend').hide(); } function showWindsLayer(){ loadWindsLayerIfEmpty(); $('.leaflet-overlay-pane').show(); $('a.logo').show(); $('#legend').show(); } function hideFiresLayer(){ layerCollection.fires.forEach( function(layer){ map.removeLayer(layer); }); } function showFiresLayer() { loadFiresLayerIfEmpty(); layerCollection.fires.forEach( function(layer){ layer.addTo(map); }); } function hideWeatherLayer(){ layerCollection.weather.forEach( function(layer){ map.removeLayer(layer); }); } function showWeatherLayer(){ loadWeatherLayerIfEmpty(); layerCollection.weather.forEach( function(layer){ console.log(layer); layer.addTo(map); }); } function hideProtectedAreasLayer(){ layerCollection.protected_areas.forEach( function(layer){ map.removeLayer(layer); }); } function showProtectedAreasLayer(){ loadProtectedAreasLayerIfEmpty(); layerCollection.protected_areas.forEach( function(layer){ layer.addTo(map); }); } function initializeMapOptions(pMap, pMapView){ /* Routing */ route = L.Routing.control({ waypoints: [], routeWhileDragging: false, createMarker: function() { return null; }, router: L.Routing.mapbox('pk.eyJ1IjoibHVtdXJpbGxvIiwiYSI6IlVRTlZkbFkifQ.nFkWwVMJm_5mUy-9ye65Og') }); route.addTo(pMap); loadIcons(); //Capturing the moveend event from the map pMap.on('moveend', function() { checkZoomLevel(); }); //Data from the backend MODISLayer = new L.GeoJSON(null, { onEachFeature:onEachFeature }).addTo(pMap); showFiresLayer(); if ( pMapView.hasClass("weather_perspective") ){ showWeatherLayer(); }; if ( pMapView.hasClass("forests") ){ showForestLayer(); }; if ( pMapView.hasClass("protected_areas") ){ showProtectedAreasLayer(); }; } function isWindyMap() { return $("#windyty").length == 1; } //region UI Cleaning function hideControls(){ $('.leaflet-control-container').hide(); } function relocateWindyLogo(){ var logoView = $('a.logo'); logoView.css( { 'right': '10px', 'top': '5px', 'left': 'initial', 'bottom': 'initial' } ); } function relocateLegend(){ var legendView = $('#legend'); legendView.css( { 'right': '0px', 'top': '50px', 'left': 'initial', 'bottom': 'initial' } ); } function overrideUI(){ hideControls(); relocateWindyLogo(); relocateLegend(); } function overrideWindyMetrics(){ // Observe for changes on legend to be sure that is placed correctly // https://stackoverflow.com/questions/43622161/javascript-callback-function-when-an-elements-attributes-change var legend = document.getElementById('legend'); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log("legend is changing!"); // run some change when the style is mutated overrideUI(); }); }); observer.observe(legend, { attributes: true }); // Change metric W.overlays.wind.setMetric( 'km/h' ); } function windytyMain(pMap) { map = pMap; //global ref setBaseMap(map); // overrideWindyMetrics(); initializeMapOptions(pMap, $('#windyty') ); downloadMODISData(); //ui cleaning overrideUI(); } function setBaseMap(pMap){ L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>', maxZoom: 18 }).addTo(pMap); } //endregion function defaultMain(){ //Map where the data will be displayed map = L.map('map').setView([10.07568504578726, -84.31182861328125], 8); //Some setting to the general map setBaseMap(map); } $(function() { if ( !isWindyMap() ) { defaultMain(); initializeMapOptions( map, $('#map') ); downloadMODISData(); } });
Fix bad latitude and longitude calls.
app/assets/javascripts/maps.js
Fix bad latitude and longitude calls.
<ide><path>pp/assets/javascripts/maps.js <ide> function addReportLocation(){ <ide> <ide> var center = map.getBounds().getCenter(); <del> var latitude = center.latitude; <del> var longitude = center.longitude; <add> var latitude = center.lat; <add> var longitude = center.lng; <ide> <ide> // Initialize marker if null <ide> if ( reportMarker === null || reportMarker === undefined ) {
Java
apache-2.0
a13829aa74f70b82c429b53de684a606e6cf301b
0
vanitasvitae/Smack,Flowdalic/Smack,Flowdalic/Smack,igniterealtime/Smack,Flowdalic/Smack,vanitasvitae/Smack,vanitasvitae/Smack,igniterealtime/Smack,igniterealtime/Smack
/** * * Copyright 2014-2019 Florian Schmaus * * 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.jivesoftware.smack; import java.util.ArrayList; import java.util.List; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.util.dns.HostAddress; import org.jxmpp.jid.Jid; /** * Smack uses SmackExceptions for errors that are not defined by any XMPP specification. * * @author Florian Schmaus */ public abstract class SmackException extends Exception { /** * */ private static final long serialVersionUID = 1844674365368214458L; /** * Creates a new SmackException with the Throwable that was the root cause of the exception. * * @param wrappedThrowable the root cause of the exception. */ protected SmackException(Throwable wrappedThrowable) { super(wrappedThrowable); } protected SmackException(String message) { super(message); } protected SmackException(String message, Throwable wrappedThrowable) { super(message, wrappedThrowable); } protected SmackException() { } /** * Exception thrown always when there was no response to an request within the stanza reply timeout of the used * connection instance. You can modify (e.g. increase) the stanza reply timeout with * {@link XMPPConnection#setReplyTimeout(long)}. */ public static final class NoResponseException extends SmackException { /** * */ private static final long serialVersionUID = -6523363748984543636L; private final StanzaFilter filter; private NoResponseException(String message) { this(message, null); } private NoResponseException(String message, StanzaFilter filter) { super(message); this.filter = filter; } /** * Get the filter that was used to collect the response. * * @return the used filter or <code>null</code>. */ public StanzaFilter getFilter() { return filter; } public static NoResponseException newWith(XMPPConnection connection, String waitingFor) { final StringBuilder sb = getWaitingFor(connection); sb.append(" While waiting for ").append(waitingFor); return new NoResponseException(sb.toString()); } public static NoResponseException newWith(XMPPConnection connection, StanzaCollector collector, boolean stanzaCollectorCancelled) { return newWith(connection, collector.getStanzaFilter(), stanzaCollectorCancelled); } public static NoResponseException newWith(XMPPConnection connection, StanzaFilter filter) { return newWith(connection, filter, false); } public static NoResponseException newWith(XMPPConnection connection, StanzaFilter filter, boolean stanzaCollectorCancelled) { final StringBuilder sb = getWaitingFor(connection); if (stanzaCollectorCancelled) { sb.append(" StanzaCollector has been cancelled."); } sb.append(" Waited for response using: "); if (filter != null) { sb.append(filter.toString()); } else { sb.append("No filter used or filter was 'null'"); } sb.append('.'); return new NoResponseException(sb.toString(), filter); } private static StringBuilder getWaitingFor(XMPPConnection connection) { final long replyTimeout = connection.getReplyTimeout(); final StringBuilder sb = new StringBuilder(256); sb.append("No response received within reply timeout. Timeout was " + replyTimeout + "ms (~" + replyTimeout / 1000 + "s)."); return sb; } } public static class NotLoggedInException extends SmackException { /** * */ private static final long serialVersionUID = 3216216839100019278L; public NotLoggedInException() { super("Client is not logged in"); } } public static class AlreadyLoggedInException extends SmackException { /** * */ private static final long serialVersionUID = 5011416918049935231L; public AlreadyLoggedInException() { super("Client is already logged in"); } } public static class AlreadyConnectedException extends SmackException { /** * */ private static final long serialVersionUID = 5011416918049135231L; public AlreadyConnectedException() { super("Client is already connected"); } } public static class NotConnectedException extends SmackException { /** * */ private static final long serialVersionUID = 9197980400776001173L; public NotConnectedException() { this(null); } public NotConnectedException(String optionalHint) { super("Client is not, or no longer, connected." + (optionalHint != null ? ' ' + optionalHint : "")); } public NotConnectedException(XMPPConnection connection, String details) { super("The connection " + connection.toString() + " is no longer connected. " + details); } public NotConnectedException(XMPPConnection connection, StanzaFilter stanzaFilter) { super("The connection " + connection + " is no longer connected while waiting for response with " + stanzaFilter); } public NotConnectedException(XMPPConnection connection, StanzaFilter stanzaFilter, Exception connectionException) { super("The connection " + connection + " is no longer connected while waiting for response with " + stanzaFilter + " because of " + connectionException, connectionException); } } public static class IllegalStateChangeException extends SmackException { /** * */ private static final long serialVersionUID = -1766023961577168927L; public IllegalStateChangeException() { } } public abstract static class SecurityRequiredException extends SmackException { /** * */ private static final long serialVersionUID = 384291845029773545L; public SecurityRequiredException(String message) { super(message); } } public static class SecurityRequiredByClientException extends SecurityRequiredException { /** * */ private static final long serialVersionUID = 2395325821201543159L; public SecurityRequiredByClientException() { super("SSL/TLS required by client but not supported by server"); } } public static class SecurityRequiredByServerException extends SecurityRequiredException { /** * */ private static final long serialVersionUID = 8268148813117631819L; public SecurityRequiredByServerException() { super("SSL/TLS required by server but disabled in client"); } } public static class SecurityNotPossibleException extends SmackException { /** * */ private static final long serialVersionUID = -6836090872690331336L; public SecurityNotPossibleException(String message) { super(message); } } /** * ConnectionException is thrown if Smack is unable to connect to all hosts of a given XMPP * service. The failed hosts can be retrieved with * {@link ConnectionException#getFailedAddresses()}, which will have the exception causing the * connection failure set and retrievable with {@link HostAddress#getExceptions()}. */ public static class ConnectionException extends SmackException { /** * */ private static final long serialVersionUID = 1686944201672697996L; private final List<HostAddress> failedAddresses; public ConnectionException(Throwable wrappedThrowable) { super(wrappedThrowable); failedAddresses = new ArrayList<>(0); } private ConnectionException(String message, List<HostAddress> failedAddresses) { super(message); this.failedAddresses = failedAddresses; } public static ConnectionException from(List<HostAddress> failedAddresses) { final String DELIMITER = ", "; StringBuilder sb = new StringBuilder("The following addresses failed: "); for (HostAddress hostAddress : failedAddresses) { sb.append(hostAddress.getErrorMessage()); sb.append(DELIMITER); } // Remove the last delimiter sb.setLength(sb.length() - DELIMITER.length()); return new ConnectionException(sb.toString(), failedAddresses); } public List<HostAddress> getFailedAddresses() { return failedAddresses; } } public static class ConnectionUnexpectedTerminatedException extends SmackException { private static final long serialVersionUID = 1L; public ConnectionUnexpectedTerminatedException(Throwable wrappedThrowable) { super(wrappedThrowable); } } public static class FeatureNotSupportedException extends SmackException { /** * */ private static final long serialVersionUID = 4713404802621452016L; private final String feature; private final Jid jid; public FeatureNotSupportedException(String feature) { this(feature, null); } public FeatureNotSupportedException(String feature, Jid jid) { super(feature + " not supported" + (jid == null ? "" : " by '" + jid + "'")); this.jid = jid; this.feature = feature; } /** * Get the feature which is not supported. * * @return the feature which is not supported */ public String getFeature() { return feature; } /** * Get JID which does not support the feature. The JID can be null in cases when there are * multiple JIDs queried for this feature. * * @return the JID which does not support the feature, or null */ public Jid getJid() { return jid; } } public static class ResourceBindingNotOfferedException extends SmackException { /** * */ private static final long serialVersionUID = 2346934138253437571L; public ResourceBindingNotOfferedException() { super("Resource binding was not offered by server"); } } /** * A Smack exception wrapping another exception. Note that usage of this class is consider bad practice. This class * will eventually be marked deprecated and removed. */ public static class SmackWrappedException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackWrappedException(Exception exception) { super(exception); } public SmackWrappedException(String message, Exception exception) { super(message, exception); } } /** * A Smack exception wrapping a text message. Note that usage of this class is consider bad practice. This class * will eventually be marked deprecated and removed. */ public static class SmackMessageException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackMessageException(String message) { super(message); } } public static class SmackSaslException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackSaslException(Exception exception) { super(exception); } public SmackSaslException(String message) { super(message); } public SmackSaslException(String message, Exception exception) { super(message, exception); } } }
smack-core/src/main/java/org/jivesoftware/smack/SmackException.java
/** * * Copyright 2014-2019 Florian Schmaus * * 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.jivesoftware.smack; import java.util.ArrayList; import java.util.List; import org.jivesoftware.smack.filter.StanzaFilter; import org.jivesoftware.smack.util.dns.HostAddress; import org.jxmpp.jid.Jid; /** * Smack uses SmackExceptions for errors that are not defined by any XMPP specification. * * @author Florian Schmaus */ public abstract class SmackException extends Exception { /** * */ private static final long serialVersionUID = 1844674365368214458L; /** * Creates a new SmackException with the Throwable that was the root cause of the exception. * * @param wrappedThrowable the root cause of the exception. */ protected SmackException(Throwable wrappedThrowable) { super(wrappedThrowable); } protected SmackException(String message) { super(message); } protected SmackException(String message, Throwable wrappedThrowable) { super(message, wrappedThrowable); } protected SmackException() { } /** * Exception thrown always when there was no response to an request within the stanza reply timeout of the used * connection instance. You can modify (e.g. increase) the stanza reply timeout with * {@link XMPPConnection#setReplyTimeout(long)}. */ public static final class NoResponseException extends SmackException { /** * */ private static final long serialVersionUID = -6523363748984543636L; private final StanzaFilter filter; private NoResponseException(String message) { this(message, null); } private NoResponseException(String message, StanzaFilter filter) { super(message); this.filter = filter; } /** * Get the filter that was used to collect the response. * * @return the used filter or <code>null</code>. */ public StanzaFilter getFilter() { return filter; } public static NoResponseException newWith(XMPPConnection connection, String waitingFor) { final StringBuilder sb = getWaitingFor(connection); sb.append(" While waiting for ").append(waitingFor); return new NoResponseException(sb.toString()); } public static NoResponseException newWith(XMPPConnection connection, StanzaCollector collector, boolean stanzaCollectorCancelled) { return newWith(connection, collector.getStanzaFilter(), stanzaCollectorCancelled); } public static NoResponseException newWith(XMPPConnection connection, StanzaFilter filter) { return newWith(connection, filter, false); } public static NoResponseException newWith(XMPPConnection connection, StanzaFilter filter, boolean stanzaCollectorCancelled) { final StringBuilder sb = getWaitingFor(connection); if (stanzaCollectorCancelled) { sb.append(" StanzaCollector has been cancelled."); } sb.append(" Waited for response using: "); if (filter != null) { sb.append(filter.toString()); } else { sb.append("No filter used or filter was 'null'"); } sb.append('.'); return new NoResponseException(sb.toString(), filter); } private static StringBuilder getWaitingFor(XMPPConnection connection) { final long replyTimeout = connection.getReplyTimeout(); final StringBuilder sb = new StringBuilder(256); sb.append("No response received within reply timeout. Timeout was " + replyTimeout + "ms (~" + replyTimeout / 1000 + "s)."); return sb; } } public static class NotLoggedInException extends SmackException { /** * */ private static final long serialVersionUID = 3216216839100019278L; public NotLoggedInException() { super("Client is not logged in"); } } public static class AlreadyLoggedInException extends SmackException { /** * */ private static final long serialVersionUID = 5011416918049935231L; public AlreadyLoggedInException() { super("Client is already logged in"); } } public static class AlreadyConnectedException extends SmackException { /** * */ private static final long serialVersionUID = 5011416918049135231L; public AlreadyConnectedException() { super("Client is already connected"); } } public static class NotConnectedException extends SmackException { /** * */ private static final long serialVersionUID = 9197980400776001173L; public NotConnectedException() { this(null); } public NotConnectedException(String optionalHint) { super("Client is not, or no longer, connected." + (optionalHint != null ? ' ' + optionalHint : "")); } public NotConnectedException(XMPPConnection connection, String details) { super("The connection " + connection.toString() + " is no longer connected. " + details); } public NotConnectedException(XMPPConnection connection, StanzaFilter stanzaFilter) { super("The connection " + connection + " is no longer connected while waiting for response with " + stanzaFilter); } public NotConnectedException(XMPPConnection connection, StanzaFilter stanzaFilter, Exception connectionException) { super("The connection " + connection + " is no longer connected while waiting for response with " + stanzaFilter + " because of " + connectionException, connectionException); } } public static class IllegalStateChangeException extends SmackException { /** * */ private static final long serialVersionUID = -1766023961577168927L; public IllegalStateChangeException() { } } public abstract static class SecurityRequiredException extends SmackException { /** * */ private static final long serialVersionUID = 384291845029773545L; public SecurityRequiredException(String message) { super(message); } } public static class SecurityRequiredByClientException extends SecurityRequiredException { /** * */ private static final long serialVersionUID = 2395325821201543159L; public SecurityRequiredByClientException() { super("SSL/TLS required by client but not supported by server"); } } public static class SecurityRequiredByServerException extends SecurityRequiredException { /** * */ private static final long serialVersionUID = 8268148813117631819L; public SecurityRequiredByServerException() { super("SSL/TLS required by server but disabled in client"); } } public static class SecurityNotPossibleException extends SmackException { /** * */ private static final long serialVersionUID = -6836090872690331336L; public SecurityNotPossibleException(String message) { super(message); } } /** * ConnectionException is thrown if Smack is unable to connect to all hosts of a given XMPP * service. The failed hosts can be retrieved with * {@link ConnectionException#getFailedAddresses()}, which will have the exception causing the * connection failure set and retrievable with {@link HostAddress#getExceptions()}. */ public static class ConnectionException extends SmackException { /** * */ private static final long serialVersionUID = 1686944201672697996L; private final List<HostAddress> failedAddresses; public ConnectionException(Throwable wrappedThrowable) { super(wrappedThrowable); failedAddresses = new ArrayList<>(0); } private ConnectionException(String message, List<HostAddress> failedAddresses) { super(message); this.failedAddresses = failedAddresses; } public static ConnectionException from(List<HostAddress> failedAddresses) { final String DELIMITER = ", "; StringBuilder sb = new StringBuilder("The following addresses failed: "); for (HostAddress hostAddress : failedAddresses) { sb.append(hostAddress.getErrorMessage()); sb.append(DELIMITER); } // Remove the last delimiter sb.setLength(sb.length() - DELIMITER.length()); return new ConnectionException(sb.toString(), failedAddresses); } public List<HostAddress> getFailedAddresses() { return failedAddresses; } } public static class ConnectionUnexpectedTerminatedException extends SmackException { private static final long serialVersionUID = 1L; public ConnectionUnexpectedTerminatedException(Throwable wrappedThrowable) { super(wrappedThrowable); } } public static class FeatureNotSupportedException extends SmackException { /** * */ private static final long serialVersionUID = 4713404802621452016L; private final String feature; private final Jid jid; public FeatureNotSupportedException(String feature) { this(feature, null); } public FeatureNotSupportedException(String feature, Jid jid) { super(feature + " not supported" + (jid == null ? "" : " by '" + jid + "'")); this.jid = jid; this.feature = feature; } /** * Get the feature which is not supported. * * @return the feature which is not supported */ public String getFeature() { return feature; } /** * Get JID which does not support the feature. The JID can be null in cases when there are * multiple JIDs queried for this feature. * * @return the JID which does not support the feature, or null */ public Jid getJid() { return jid; } } public static class ResourceBindingNotOfferedException extends SmackException { /** * */ private static final long serialVersionUID = 2346934138253437571L; public ResourceBindingNotOfferedException() { super("Resource binding was not offered by server"); } } public static class SmackWrappedException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackWrappedException(Exception exception) { super(exception); } public SmackWrappedException(String message, Exception exception) { super(message, exception); } } public static class SmackMessageException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackMessageException(String message) { super(message); } } public static class SmackSaslException extends SmackException { /** * */ private static final long serialVersionUID = 1L; public SmackSaslException(Exception exception) { super(exception); } public SmackSaslException(String message) { super(message); } public SmackSaslException(String message, Exception exception) { super(message, exception); } } }
Add javadoc to Smack(Message|Wrapped)Exception
smack-core/src/main/java/org/jivesoftware/smack/SmackException.java
Add javadoc to Smack(Message|Wrapped)Exception
<ide><path>mack-core/src/main/java/org/jivesoftware/smack/SmackException.java <ide> } <ide> } <ide> <add> /** <add> * A Smack exception wrapping another exception. Note that usage of this class is consider bad practice. This class <add> * will eventually be marked deprecated and removed. <add> */ <ide> public static class SmackWrappedException extends SmackException { <ide> <ide> /** <ide> } <ide> } <ide> <add> /** <add> * A Smack exception wrapping a text message. Note that usage of this class is consider bad practice. This class <add> * will eventually be marked deprecated and removed. <add> */ <ide> public static class SmackMessageException extends SmackException { <ide> <ide> /**
Java
apache-2.0
c270ac0af9cda9e2c67d3dcff3fabd52b9ff4f5f
0
polypmer/whale,polypmer/whale,polypmer/whale,polypmer/starwhale,polypmer/starwhale,polypmer/starwhale
package com.everythingisreally; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; import java.util.Iterator; //TODO: FIND SWEET SPOT // FOR: health drain and star generation and whale speed public class StarWhale extends ApplicationAdapter { private Texture smallStarImage; private Texture bigStarImage; private Texture whaleImage; private Sound plopSound; // Set Up the Camera and Sprite Batch so that image scales private OrthographicCamera camera; private SpriteBatch batch; // The Programmable Shapes private Whale whale; private Array<Rectangle> smallStars; private Array<Rectangle> bigStars; // Itervals for Star spawn and Drain health private long lastBigStarTime; private long lastDrainTime; private long lastStarTime; // Whale Movement private int RIGHT = 0; private int LEFT = 1; private int whaleDirection = 0; //lets say 0 is right? private float x_start = 800 / 2 - 32 / 2; // x origin private float y_start = 70; // y origin private float w_start = 32; // width private float h_start = 64; // height // Health and Score private String starScore; BitmapFont scoreBitmap; private String whaleHealth; BitmapFont healthBitmap; @Override public void create () { //Health and Score Initial to 100 and 0 starScore = "score: 0"; scoreBitmap = new BitmapFont(); whaleHealth = "Health: 100"; healthBitmap = new BitmapFont(); //Star Textures smallStarImage = new Texture(Gdx.files.internal("small_star.png")); bigStarImage = new Texture(Gdx.files.internal("big_star.png")); // Whale Textures? whaleImage = new Texture(Gdx.files.internal("star_whale.png")); // Sounds? TODO: Classy music plopSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav")); // Scale Textures ETC to same size camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 1150); // Sprite Batch batch = new SpriteBatch(); // create the Whale, extending Rectangle whale = new Whale(x_start, y_start, w_start, h_start, whaleImage); // create the raindrops array and spawn the first raindrop smallStars = new Array<Rectangle>(); bigStars = new Array<Rectangle>(); spawnSmallStar(); //spawnBigStar(); // Start draining health, whale.drainHealth(); lastDrainTime = TimeUtils.nanoTime(); } private void spawnSmallStar() { Rectangle smallStar = new Rectangle(); smallStar.x = MathUtils.random(0, 800 - 64); smallStar.y = 1150; smallStar.width = 19; smallStar.height = 19; smallStars.add(smallStar); lastStarTime = TimeUtils.nanoTime(); } private void spawnBigStar() { Rectangle bigStar = new Rectangle(); bigStar.x = MathUtils.random(0, 800 - 64); bigStar.y = 1150; bigStar.width = 29; bigStar.height = 29; bigStars.add(bigStar); lastBigStarTime = TimeUtils.nanoTime(); } @Override public void render () { // clear the screen with a dark blue color. The // arguments to glClearColor are the red, green // blue and alpha component in the range [0,1] // of the color to be used to clear the screen. // TODO: Make Pretty Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // tell the camera to update its matrices. camera.update(); // Check Whale size //whale.refreshWhale(); // Update stats whaleHealth = "Health " + whale.getHealth(); starScore = "Score: " + whale.getScore(); // Drain Health at interval if(TimeUtils.nanoTime() - lastDrainTime > 100500000){ whale.drainHealth(); lastDrainTime = TimeUtils.nanoTime(); } // tell the SpriteBatch to render in the // coordinate system specified by the camera. batch.setProjectionMatrix(camera.combined); // begin a new batch and draw the whale and // all stars and the Score and Health batch.begin(); // Score scoreBitmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); scoreBitmap.draw(batch, starScore, 25, 100); // Health healthBitmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); healthBitmap.draw(batch, whaleHealth, 25, 130); // Whale batch.draw(whaleImage, whale.x, whale.y); // Stars for(Rectangle smallStar: smallStars) { batch.draw(smallStarImage, smallStar.x, smallStar.y); } for(Rectangle bigStar: bigStars) { batch.draw(bigStarImage, bigStar.x, bigStar.y); } batch.end(); // process user input // INPUT must be JUST touched, else its buggy if(Gdx.input.justTouched()) { if(whaleDirection == RIGHT) { whaleDirection = LEFT; } else if(whaleDirection == LEFT) { whaleDirection = RIGHT; } } // The movements! if(whaleDirection == RIGHT) whale.x -= 250 * Gdx.graphics.getDeltaTime(); if(whaleDirection == LEFT) whale.x += 250 * Gdx.graphics.getDeltaTime(); // make sure the whale stays within the screen bounds if(whale.x < 0) whale.x = 0; if(whale.x > 800 - 32) whale.x = 800 - 32; // check if we need to create a new star TODO: Find sweet Spot if(TimeUtils.nanoTime() - lastStarTime > 99919990) spawnSmallStar(); // Falling Stars, and Collision Checking // Remove below screen and add health/score when collision Iterator<Rectangle> iter = smallStars.iterator(); // the SMALL star updater while(iter.hasNext()){ Rectangle smallStar = iter.next(); smallStar.y -= 250 * Gdx.graphics.getDeltaTime(); if(smallStar.y + 19 < 0) iter.remove(); if(smallStar.overlaps(whale)) { plopSound.play(); iter.remove(); whale.addScore(1); whale.addHealth(1); } } } // Clean Up! @Override public void dispose() { // dispose of all the native resources smallStarImage.dispose(); bigStarImage.dispose(); whaleImage.dispose(); plopSound.dispose(); batch.dispose(); } }
core/src/com/everythingisreally/StarWhale.java
package com.everythingisreally; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.TimeUtils; import java.util.Iterator; //TODO: Create Star Class public class StarWhale extends ApplicationAdapter { private Texture smallStarImage; private Texture bigStarImage; private Texture whaleImage; private Sound plopSound; // Set Up the Camera and Sprite Batch so that image scales private OrthographicCamera camera; private SpriteBatch batch; // The Programmable Shapes private Whale whale; private Array<Rectangle> smallStars; private Array<Rectangle> bigStars; // Itervals for Star spawn and Drain health private long lastBigStarTime; private long lastDrainTime; private long lastStarTime; // Whale Movement private int RIGHT = 0; private int LEFT = 1; private int whaleDirection = 0; //lets say 0 is right? private float x_start = 800 / 2 - 32 / 2; // x origin private float y_start = 70; // y origin private float w_start = 32; // width private float h_start = 64; // height // Health and Score private String starScore; BitmapFont scoreBitmap; private String whaleHealth; BitmapFont healthBitmap; @Override public void create () { //Health and Score Initial to 100 and 0 starScore = "score: 0"; scoreBitmap = new BitmapFont(); whaleHealth = "Health: 100"; healthBitmap = new BitmapFont(); //Star Textures smallStarImage = new Texture(Gdx.files.internal("small_star.png")); bigStarImage = new Texture(Gdx.files.internal("big_star.png")); // Whale Textures? whaleImage = new Texture(Gdx.files.internal("star_whale.png")); // Sounds? TODO: Classy music plopSound = Gdx.audio.newSound(Gdx.files.internal("drop.wav")); // Scale Textures ETC to same size camera = new OrthographicCamera(); camera.setToOrtho(false, 800, 1150); // Sprite Batch batch = new SpriteBatch(); // create the Whale, extending Rectangle whale = new Whale(x_start, y_start, w_start, h_start, whaleImage); // create the raindrops array and spawn the first raindrop smallStars = new Array<Rectangle>(); bigStars = new Array<Rectangle>(); spawnSmallStar(); //spawnBigStar(); // Start draining health, whale.drainHealth(); lastDrainTime = TimeUtils.nanoTime(); } private void spawnBigStar() { } private void spawnSmallStar() { Rectangle smallStar = new Rectangle(); smallStar.x = MathUtils.random(0, 800 - 64); smallStar.y = 1150; smallStar.width = 19; smallStar.height = 19; smallStars.add(smallStar); lastStarTime = TimeUtils.nanoTime(); } @Override public void render () { // clear the screen with a dark blue color. The // arguments to glClearColor are the red, green // blue and alpha component in the range [0,1] // of the color to be used to clear the screen. // TODO: Make Pretty Gdx.gl.glClearColor(0, 0, 0.2f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // tell the camera to update its matrices. camera.update(); // Check Whale size //whale.refreshWhale(); // Update stats whaleHealth = "Health " + whale.getHealth(); starScore = "Score: " + whale.getScore(); // Drain Health at interval if(TimeUtils.nanoTime() - lastDrainTime > 100500000){ whale.drainHealth(); lastDrainTime = TimeUtils.nanoTime(); } // tell the SpriteBatch to render in the // coordinate system specified by the camera. batch.setProjectionMatrix(camera.combined); // begin a new batch and draw the whale and // all stars and the Score and Health batch.begin(); // Score scoreBitmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); scoreBitmap.draw(batch, starScore, 25, 100); // Health healthBitmap.setColor(1.0f, 1.0f, 1.0f, 1.0f); healthBitmap.draw(batch, whaleHealth, 25, 130); // Whale batch.draw(whaleImage, whale.x, whale.y); // Stars for(Rectangle smallStar: smallStars) { batch.draw(smallStarImage, smallStar.x, smallStar.y); } for(Rectangle bigStar: bigStars) { batch.draw(bigStarImage, bigStar.x, bigStar.y); } batch.end(); // process user input // INPUT must be JUST touched, else its buggy if(Gdx.input.justTouched()) { if(whaleDirection == RIGHT) { whaleDirection = LEFT; } else if(whaleDirection == LEFT) { whaleDirection = RIGHT; } } // The movements! if(whaleDirection == RIGHT) whale.x -= 250 * Gdx.graphics.getDeltaTime(); if(whaleDirection == LEFT) whale.x += 250 * Gdx.graphics.getDeltaTime(); // make sure the whale stays within the screen bounds if(whale.x < 0) whale.x = 0; if(whale.x > 800 - 32) whale.x = 800 - 32; // check if we need to create a new star if(TimeUtils.nanoTime() - lastStarTime > 1000000000) spawnSmallStar(); // The Spawning from Array? // Remove below screen and add health/score when collision Iterator<Rectangle> iter = smallStars.iterator(); // the SMALL star updater while(iter.hasNext()){ Rectangle smallStar = iter.next(); smallStar.y -= 250 * Gdx.graphics.getDeltaTime(); if(smallStar.y + 19 < 0) iter.remove(); if(smallStar.overlaps(whale)) { plopSound.play(); iter.remove(); whale.addScore(1); whale.addHealth(1); } } } // Clean Up! @Override public void dispose() { // dispose of all the native resources smallStarImage.dispose(); bigStarImage.dispose(); whaleImage.dispose(); plopSound.dispose(); batch.dispose(); } }
implemented falling stars frequency which makes sense
core/src/com/everythingisreally/StarWhale.java
implemented falling stars frequency which makes sense
<ide><path>ore/src/com/everythingisreally/StarWhale.java <ide> <ide> import java.util.Iterator; <ide> <del>//TODO: Create Star Class <add>//TODO: FIND SWEET SPOT <add>// FOR: health drain and star generation and whale speed <ide> public class StarWhale extends ApplicationAdapter { <ide> <ide> private Texture smallStarImage; <ide> <ide> } <ide> <del> private void spawnBigStar() { <del> } <del> <ide> private void spawnSmallStar() { <ide> Rectangle smallStar = new Rectangle(); <ide> smallStar.x = MathUtils.random(0, 800 - 64); <ide> smallStar.height = 19; <ide> smallStars.add(smallStar); <ide> lastStarTime = TimeUtils.nanoTime(); <add> } <add> <add> private void spawnBigStar() { <add> Rectangle bigStar = new Rectangle(); <add> bigStar.x = MathUtils.random(0, 800 - 64); <add> bigStar.y = 1150; <add> bigStar.width = 29; <add> bigStar.height = 29; <add> bigStars.add(bigStar); <add> lastBigStarTime = TimeUtils.nanoTime(); <ide> } <ide> <ide> @Override <ide> if(whale.x < 0) whale.x = 0; <ide> if(whale.x > 800 - 32) whale.x = 800 - 32; <ide> <del> // check if we need to create a new star <del> if(TimeUtils.nanoTime() - lastStarTime > 1000000000) spawnSmallStar(); <del> <del> // The Spawning from Array? <add> // check if we need to create a new star TODO: Find sweet Spot <add> if(TimeUtils.nanoTime() - lastStarTime > 99919990) spawnSmallStar(); <add> <add> <add> // Falling Stars, and Collision Checking <ide> // Remove below screen and add health/score when collision <ide> Iterator<Rectangle> iter = smallStars.iterator(); <ide> // the SMALL star updater
Java
bsd-3-clause
6a2b28a8baf0001f0ad4bccfe5ef23ddd2f6521a
0
NCIP/cananolab,NCIP/cananolab,NCIP/cananolab
package gov.nih.nci.calab.domain.nano.characterization.physical; import gov.nih.nci.calab.domain.Measurement; public class SurfaceChemistry { private Long id; private String molecule; private Measurement density; public SurfaceChemistry() { super(); // TODO Auto-generated constructor stub } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Measurement getDensity() { return density; } public void setDensity(Measurement density) { this.density = density; } public String getMolecule() { return molecule; } public void setMolecule(String molecule) { this.molecule = molecule; } }
src/gov/nih/nci/calab/domain/nano/characterization/physical/SurfaceChemistry.java
package gov.nih.nci.calab.domain.nano.characterization.physical; import gov.nih.nci.calab.domain.Measurement; public class SurfaceChemistry { private String molecule; private Measurement density; public SurfaceChemistry() { super(); // TODO Auto-generated constructor stub } public Measurement getDensity() { return density; } public void setDensity(Measurement density) { this.density = density; } public String getMolecule() { return molecule; } public void setMolecule(String molecule) { this.molecule = molecule; } }
Added ID SVN-Revision: 2025
src/gov/nih/nci/calab/domain/nano/characterization/physical/SurfaceChemistry.java
Added ID
<ide><path>rc/gov/nih/nci/calab/domain/nano/characterization/physical/SurfaceChemistry.java <ide> <ide> public class SurfaceChemistry { <ide> <add> private Long id; <ide> private String molecule; <ide> private Measurement density; <ide> <ide> public SurfaceChemistry() { <ide> super(); <ide> // TODO Auto-generated constructor stub <add> } <add> <add> public Long getId() { <add> return id; <add> } <add> <add> public void setId(Long id) { <add> this.id = id; <ide> } <ide> <ide> public Measurement getDensity() { <ide> public void setMolecule(String molecule) { <ide> this.molecule = molecule; <ide> } <del> <del> <ide> }
Java
agpl-3.0
dbeb77ff99b770b5a9d20061290518cf7f06c892
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
3b70386e-2e61-11e5-9284-b827eb9e62be
hello.java
3b6ad5ea-2e61-11e5-9284-b827eb9e62be
3b70386e-2e61-11e5-9284-b827eb9e62be
hello.java
3b70386e-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>3b6ad5ea-2e61-11e5-9284-b827eb9e62be <add>3b70386e-2e61-11e5-9284-b827eb9e62be
Java
apache-2.0
e487d15e36357b13546e24f8a89698bdc9188d95
0
Jasig/SurveyPortlet,Jasig/SurveyPortlet,bjagg/SurveyPortlet,doodelicious/SurveyPortlet,bjagg/SurveyPortlet,bjagg/SurveyPortlet,andrewstuart/SurveyPortlet,doodelicious/SurveyPortlet,Jasig/SurveyPortlet,andrewstuart/SurveyPortlet
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.portlet.survey.mvc.service; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.apache.commons.lang.Validate; import org.jasig.portlet.survey.IVariantStrategy; import org.jasig.portlet.survey.PublishedState; import org.jasig.portlet.survey.mvc.service.ISurveyDataService; import org.jasig.portlet.survey.service.dto.*; import org.jasig.portlet.survey.service.jpa.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; /** * Service class for CRUD operations and moving to and from the business object models and the JPA impl for a survey. * @since 1.0 */ @Service public class JpaSurveyDataService implements ISurveyDataService { public static final String TABLENAME_PREFIX = "SURVEY_"; @Autowired private IJpaSurveyDao jpaSurveyDao; private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private ISurveyMapper surveyMapper; @Autowired private IVariantStrategy variantStrategy; /** * * @param surveyId * @param questionId * @param surveyQuestion * @return */ @Transactional @Override public boolean addQuestionToSurvey(Long surveyId, Long questionId, SurveyQuestionDTO surveyQuestion) { Validate.isTrue( surveyId != null && questionId != null, "Survey and question cannot be null"); JpaSurveyQuestion sq = new JpaSurveyQuestion(); sq.setNumAllowedAnswers( surveyQuestion.getNumAllowedAnswers()); sq.setSequence( surveyQuestion.getSequence()); JpaSurveyQuestion newSurveyQuestion = jpaSurveyDao.attachQuestionToSurvey(surveyId, questionId, sq); return newSurveyQuestion != null; } /** * * @param questionId * @param answer * @return */ @Transactional @Override public AnswerDTO createAnswerForQuestion(Long questionId, AnswerDTO answer) { throw new UnsupportedOperationException("Not supported yet."); } /** * Create a {@link JpaQuestion} from the data in question * * @param question * @return */ @Transactional @Override public QuestionDTO createQuestion(QuestionDTO question) { JpaQuestion jpaQuestion = surveyMapper.toJpaQuestion(question); jpaQuestion = jpaSurveyDao.createQuestion(jpaQuestion); QuestionDTO newQuestion = surveyMapper.toQuestion(jpaQuestion); return newQuestion; } /** * Create a {@link JpaSurvey} from the data in survey * * @param survey * @return */ @Transactional @Override public SurveyDTO createSurvey(SurveyDTO survey) { // remove questions/answers if they are present - only create the survey JpaSurvey jpaSurvey = surveyMapper.toJpaSurvey(survey); jpaSurvey.setLastUpdateDate(new Timestamp(new Date().getTime())); jpaSurvey = jpaSurveyDao.createSurvey(jpaSurvey); return surveyMapper.toSurvey(jpaSurvey); } @Transactional @Override public ITextGroup createTextGroup(ITextGroup textGroup) { JpaSurveyText jpaSurveyText = new JpaSurveyText(); JpaSurveyTextPK newId = new JpaSurveyTextPK(); newId.setKey(textGroup.getKey()); newId.setVariant(textGroup.getVariant()); jpaSurveyText.setId(newId); jpaSurveyText.setAltText(textGroup.getAltText()); jpaSurveyText.setDefinitionText(textGroup.getDefinitionText()); jpaSurveyText.setHelpText(textGroup.getHelpText()); jpaSurveyText.setText(textGroup.getText()); return jpaSurveyDao.createSurveyText(jpaSurveyText); } /** * Return all surveys * * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<SurveyDTO> getAllSurveys() { List<JpaSurvey> surveyList = jpaSurveyDao.getAllSurveys(); if (surveyList == null) { return null; } List<SurveyDTO> results = surveyMapper.toSurveyList(surveyList); for (SurveyDTO surveyDTO : results) { surveyDTO.retrieveText(this); } return results; } /** * Search for {@link JpaSurvey} specified by id. * * @param id * @return */ @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public SurveyDTO getSurvey(long id) { JpaSurvey jpaSurvey = jpaSurveyDao.getSurvey(id); if (jpaSurvey == null) { return null; } SurveyDTO result = surveyMapper.toSurvey(jpaSurvey); result.retrieveText(this); return result; } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public SurveyDTO getSurveyByName(String surveyName) { JpaSurvey jpaSurvey = jpaSurveyDao.getSurveyByCanonicalName(surveyName); if (jpaSurvey == null) { return null; } SurveyDTO result = surveyMapper.toSurvey(jpaSurvey); result.retrieveText(this); return result; } /** * Search for survey questions for the specified survey. * Return only the question data. * * @param surveyId * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<SurveyQuestionDTO> getSurveyQuestions(Long surveyId) { JpaSurvey survey = jpaSurveyDao.getSurvey(surveyId); if (survey == null) { return null; } SurveyDTO surveyDTO = surveyMapper.toSurvey(survey); return Lists.newArrayList(surveyDTO.getSurveyQuestions()); } /** * Retrieve the text group object based on the supplied key. * @see org.jasig.portlet.survey.mvc.service.ISurveyDataService#getTextGroup(java.lang.String) */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ITextGroup getTextGroup(String textKey) { return jpaSurveyDao.getText(textKey, variantStrategy.getVariantName()); } /** * Update question details including embedded answer data * * @param question * @return {@link QuestionDTO} or null on error */ @Transactional @Override public QuestionDTO updateQuestion(QuestionDTO question) { JpaQuestion existingQuestion = jpaSurveyDao.getQuestion( question.getId()); if( existingQuestion.getStatus() == PublishedState.PUBLISHED) { log.warn( "Cannot update question in PUBLISHED state"); return null; } JpaQuestion jpaQuestion = surveyMapper.toJpaQuestion(question); jpaSurveyDao.updateQuestion(jpaQuestion); return surveyMapper.toQuestion(jpaQuestion); } /** * Update base survey data. Questions/answer relationships will not be included in the update. * @param survey * @return */ @Transactional @Override public SurveyDTO updateSurvey(SurveyDTO survey) { JpaSurvey existingSurvey = jpaSurveyDao.getSurvey(survey.getId()); if( existingSurvey == null || existingSurvey.getStatus() == PublishedState.PUBLISHED) { log.warn( "Cannot update survey"); return null; } // remove question/answer elements survey.setSurveyQuestions( null); JpaSurvey jpaSurvey = surveyMapper.toJpaSurvey(survey); jpaSurvey.setLastUpdateDate(new Timestamp(new Date().getTime())); jpaSurvey = jpaSurveyDao.updateSurvey( jpaSurvey); return surveyMapper.toSurvey(jpaSurvey); } @Transactional @Override public ResponseDTO createResponse(ResponseDTO response) { JpaResponse jpaResponse = surveyMapper.toJpaResponse(response); // Touch the lastUpdated filed to match this persist jpaResponse.setLastUpdated(new Date()); jpaSurveyDao.createResponse(jpaResponse); return surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ResponseDTO getResponse(long id) { JpaResponse jpaResponse = jpaSurveyDao.getResponse(id); log.debug(jpaResponse.toString()); return jpaResponse == null ? null : surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<ResponseDTO> getResponseByUser(String user) { List<JpaResponse> responseList = jpaSurveyDao.getResponseByUser(user); if (responseList == null) { return null; } return surveyMapper.toResponseList(responseList); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ResponseDTO getResponseByUserAndSurvey(String user, long surveyId) { JpaResponse jpaResponse = jpaSurveyDao.getResponseByUserAndSurvey(user, surveyId); return jpaResponse == null ? null : surveyMapper.toResponse(jpaResponse); } @Transactional @Override public ResponseDTO updateResponse(ResponseDTO response) { JpaResponse existingResponse = jpaSurveyDao.getResponse(response.getId()); if (existingResponse == null) { log.warn("Cannot update response - does not exist", response.toString()); return null; } JpaResponse jpaResponse = surveyMapper.toJpaResponse(response); log.debug("existing response: " + existingResponse.toString()); log.debug("source DTO response: " + response.toString()); log.debug("mapped response: " + jpaResponse.toString()); // Touch the lastUpdated filed to match this persist jpaResponse.setLastUpdated(new Date()); jpaResponse = jpaSurveyDao.updateResponse(jpaResponse); log.debug("updated response: " + jpaResponse.toString()); return surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public SurveySummaryDTO getSurveySummary(Long surveyId) { List<JpaResponse> responses = jpaSurveyDao.getResponseBySurvey(surveyId); SurveySummaryDTO summary = new SurveySummaryDTO(responses); //summary.setResponses(responses); log.debug(summary.toString()); return summary; } }
src/main/java/org/jasig/portlet/survey/mvc/service/JpaSurveyDataService.java
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.jasig.portlet.survey.mvc.service; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.apache.commons.lang.Validate; import org.jasig.portlet.survey.IVariantStrategy; import org.jasig.portlet.survey.PublishedState; import org.jasig.portlet.survey.mvc.service.ISurveyDataService; import org.jasig.portlet.survey.service.dto.*; import org.jasig.portlet.survey.service.jpa.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.Lists; /** * Service class for CRUD operations and moving to and from the business object models and the JPA impl for a survey. * @since 1.0 */ @Service public class JpaSurveyDataService implements ISurveyDataService { public static final String TABLENAME_PREFIX = "SURVEY_"; @Autowired private IJpaSurveyDao jpaSurveyDao; private final Logger log = LoggerFactory.getLogger(getClass()); @Autowired private ISurveyMapper surveyMapper; @Autowired private IVariantStrategy variantStrategy; /** * * @param surveyId * @param questionId * @param surveyQuestion * @return */ @Transactional @Override public boolean addQuestionToSurvey(Long surveyId, Long questionId, SurveyQuestionDTO surveyQuestion) { Validate.isTrue( surveyId != null && questionId != null, "Survey and question cannot be null"); JpaSurveyQuestion sq = new JpaSurveyQuestion(); sq.setNumAllowedAnswers( surveyQuestion.getNumAllowedAnswers()); sq.setSequence( surveyQuestion.getSequence()); JpaSurveyQuestion newSurveyQuestion = jpaSurveyDao.attachQuestionToSurvey(surveyId, questionId, sq); return newSurveyQuestion != null; } /** * * @param questionId * @param answer * @return */ @Transactional @Override public AnswerDTO createAnswerForQuestion(Long questionId, AnswerDTO answer) { throw new UnsupportedOperationException("Not supported yet."); } /** * Create a {@link JpaQuestion} from the data in question * * @param question * @return */ @Transactional @Override public QuestionDTO createQuestion(QuestionDTO question) { JpaQuestion jpaQuestion = surveyMapper.toJpaQuestion(question); jpaQuestion = jpaSurveyDao.createQuestion(jpaQuestion); QuestionDTO newQuestion = surveyMapper.toQuestion(jpaQuestion); return newQuestion; } /** * Create a {@link JpaSurvey} from the data in survey * * @param survey * @return */ @Transactional @Override public SurveyDTO createSurvey(SurveyDTO survey) { // remove questions/answers if they are present - only create the survey JpaSurvey jpaSurvey = surveyMapper.toJpaSurvey(survey); jpaSurvey.setLastUpdateDate(new Timestamp(new Date().getTime())); jpaSurvey = jpaSurveyDao.createSurvey(jpaSurvey); return surveyMapper.toSurvey(jpaSurvey); } @Transactional @Override public ITextGroup createTextGroup(ITextGroup textGroup) { JpaSurveyText jpaSurveyText = new JpaSurveyText(); JpaSurveyTextPK newId = new JpaSurveyTextPK(); newId.setKey(textGroup.getKey()); newId.setVariant(textGroup.getVariant()); jpaSurveyText.setId(newId); jpaSurveyText.setAltText(textGroup.getAltText()); jpaSurveyText.setDefinitionText(textGroup.getDefinitionText()); jpaSurveyText.setHelpText(textGroup.getHelpText()); jpaSurveyText.setText(textGroup.getText()); return jpaSurveyDao.createSurveyText(jpaSurveyText); } /** * Return all surveys * * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<SurveyDTO> getAllSurveys() { List<JpaSurvey> surveyList = jpaSurveyDao.getAllSurveys(); if (surveyList == null) { return null; } List<SurveyDTO> results = surveyMapper.toSurveyList(surveyList); for (SurveyDTO surveyDTO : results) { surveyDTO.retrieveText(this); } return results; } /** * Search for {@link JpaSurvey} specified by id. * * @param id * @return */ @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public SurveyDTO getSurvey(long id) { JpaSurvey jpaSurvey = jpaSurveyDao.getSurvey(id); if (jpaSurvey == null) { return null; } SurveyDTO result = surveyMapper.toSurvey(jpaSurvey); result.retrieveText(this); return result; } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public SurveyDTO getSurveyByName(String surveyName) { JpaSurvey jpaSurvey = jpaSurveyDao.getSurveyByCanonicalName(surveyName); if (jpaSurvey == null) { return null; } SurveyDTO result = surveyMapper.toSurvey(jpaSurvey); result.retrieveText(this); return result; } /** * Search for survey questions for the specified survey. * Return only the question data. * * @param surveyId * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<SurveyQuestionDTO> getSurveyQuestions(Long surveyId) { JpaSurvey survey = jpaSurveyDao.getSurvey(surveyId); if (survey == null) { return null; } SurveyDTO surveyDTO = surveyMapper.toSurvey(survey); return Lists.newArrayList(surveyDTO.getSurveyQuestions()); } /** * Retrieve the text group object based on the supplied key. * @see org.jasig.portlet.survey.mvc.service.ISurveyDataService#getTextGroup(java.lang.String) */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ITextGroup getTextGroup(String textKey) { return jpaSurveyDao.getText(textKey, variantStrategy.getVariantName()); } /** * Update question details including embedded answer data * * @param question * @return {@link QuestionDTO} or null on error */ @Transactional @Override public QuestionDTO updateQuestion(QuestionDTO question) { JpaQuestion existingQuestion = jpaSurveyDao.getQuestion( question.getId()); if( existingQuestion.getStatus() == PublishedState.PUBLISHED) { log.warn( "Cannot update question in PUBLISHED state"); return null; } JpaQuestion jpaQuestion = surveyMapper.toJpaQuestion(question); jpaSurveyDao.updateQuestion(jpaQuestion); return surveyMapper.toQuestion(jpaQuestion); } /** * Update base survey data. Questions/answer relationships will not be included in the update. * @param survey * @return */ @Transactional @Override public SurveyDTO updateSurvey(SurveyDTO survey) { JpaSurvey existingSurvey = jpaSurveyDao.getSurvey(survey.getId()); if( existingSurvey == null || existingSurvey.getStatus() == PublishedState.PUBLISHED) { log.warn( "Cannot update survey"); return null; } // remove question/answer elements survey.setSurveyQuestions( null); JpaSurvey jpaSurvey = surveyMapper.toJpaSurvey(survey); jpaSurvey.setLastUpdateDate(new Timestamp(new Date().getTime())); jpaSurvey = jpaSurveyDao.updateSurvey( jpaSurvey); return surveyMapper.toSurvey(jpaSurvey); } @Transactional @Override public ResponseDTO createResponse(ResponseDTO response) { JpaResponse jpaResponse = surveyMapper.toJpaResponse(response); jpaSurveyDao.createResponse(jpaResponse); return surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ResponseDTO getResponse(long id) { JpaResponse jpaResponse = jpaSurveyDao.getResponse(id); log.debug(jpaResponse.toString()); return jpaResponse == null ? null : surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public List<ResponseDTO> getResponseByUser(String user) { List<JpaResponse> responseList = jpaSurveyDao.getResponseByUser(user); if (responseList == null) { return null; } return surveyMapper.toResponseList(responseList); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public ResponseDTO getResponseByUserAndSurvey(String user, long surveyId) { JpaResponse jpaResponse = jpaSurveyDao.getResponseByUserAndSurvey(user, surveyId); return jpaResponse == null ? null : surveyMapper.toResponse(jpaResponse); } @Transactional @Override public ResponseDTO updateResponse(ResponseDTO response) { JpaResponse existingResponse = jpaSurveyDao.getResponse(response.getId()); if (existingResponse == null) { log.warn("Cannot update response - does not exist", response.toString()); return null; } JpaResponse jpaResponse = surveyMapper.toJpaResponse(response); log.debug("existing response: " + existingResponse.toString()); log.debug("source DTO response: " + response.toString()); log.debug("mapped response: " + jpaResponse.toString()); // Touch the lastUpdated filed to match this persist jpaResponse.setLastUpdated(new Date()); jpaResponse = jpaSurveyDao.updateResponse(jpaResponse); log.debug("updated response: " + jpaResponse.toString()); return surveyMapper.toResponse(jpaResponse); } @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) @Override public SurveySummaryDTO getSurveySummary(Long surveyId) { List<JpaResponse> responses = jpaSurveyDao.getResponseBySurvey(surveyId); SurveySummaryDTO summary = new SurveySummaryDTO(responses); //summary.setResponses(responses); log.debug(summary.toString()); return summary; } }
Adding a lastUpdated fieled to the Response
src/main/java/org/jasig/portlet/survey/mvc/service/JpaSurveyDataService.java
Adding a lastUpdated fieled to the Response
<ide><path>rc/main/java/org/jasig/portlet/survey/mvc/service/JpaSurveyDataService.java <ide> @Override <ide> public ResponseDTO createResponse(ResponseDTO response) { <ide> JpaResponse jpaResponse = surveyMapper.toJpaResponse(response); <add> // Touch the lastUpdated filed to match this persist <add> jpaResponse.setLastUpdated(new Date()); <ide> jpaSurveyDao.createResponse(jpaResponse); <ide> return surveyMapper.toResponse(jpaResponse); <ide> }
Java
mit
error: pathspec 'src/Playlist.java' did not match any file(s) known to git
7b1fad393399a11f3dfaa56700c2ea1f6d4782f5
1
yige-hu/bayou
public class Playlist { }
src/Playlist.java
add src bin folders
src/Playlist.java
add src bin folders
<ide><path>rc/Playlist.java <add> <add>public class Playlist { <add> <add>}
Java
apache-2.0
656857c3ff4dbeac68a82008e917148d79100cff
0
ewestfal/rice-svn2git-test,ewestfal/rice,sonamuthu/rice-1,rojlarge/rice-kc,kuali/kc-rice,bsmith83/rice-1,sonamuthu/rice-1,gathreya/rice-kc,sonamuthu/rice-1,gathreya/rice-kc,bhutchinson/rice,kuali/kc-rice,smith750/rice,UniversityOfHawaiiORS/rice,bhutchinson/rice,jwillia/kc-rice1,jwillia/kc-rice1,bhutchinson/rice,geothomasp/kualico-rice-kc,cniesen/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,geothomasp/kualico-rice-kc,smith750/rice,cniesen/rice,smith750/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,UniversityOfHawaiiORS/rice,cniesen/rice,shahess/rice,shahess/rice,rojlarge/rice-kc,ewestfal/rice,jwillia/kc-rice1,kuali/kc-rice,jwillia/kc-rice1,ewestfal/rice-svn2git-test,smith750/rice,bhutchinson/rice,ewestfal/rice,gathreya/rice-kc,shahess/rice,ewestfal/rice,ewestfal/rice,cniesen/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,jwillia/kc-rice1,bhutchinson/rice,gathreya/rice-kc,bsmith83/rice-1,bsmith83/rice-1,UniversityOfHawaiiORS/rice,rojlarge/rice-kc,sonamuthu/rice-1,smith750/rice,UniversityOfHawaiiORS/rice,cniesen/rice,bsmith83/rice-1,shahess/rice,rojlarge/rice-kc,shahess/rice,rojlarge/rice-kc,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice
/** * Copyright 2005-2014 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.krad.demo.lookup.stackedresults; import org.junit.Test; import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase; import org.openqa.selenium.By; /** * This class performs simple tests on the stacked results lookup * * @author Kuali Rice Team ([email protected]) */ public class DemoLookUpStackedResultsAft extends WebDriverLegacyITBase { /** * /kr-krad/lookup?methodToCall=start&viewId=LookupSampleViewMultipleValuesSelectLimit&hideReturnLink=true */ public static final String BOOKMARK_URL = "/kr-krad/lookup?methodToCall=start&viewId=LookupSampleViewStackedResults&hideReturnLink=true"; /** * lookupCriteria[number] */ private static final String LOOKUP_CRITERIA_NUMBER_NAME="lookupCriteria[number]"; private static final String LOOKUP_CRITERIA_DATE="lookupCriteria[createDate]"; /** * Search */ private static final String SEARCH="Search"; /** * Clear Values */ private static final String CLEAR_VALUES="Clear Values"; @Override public String getBookmarkUrl() { return BOOKMARK_URL; } @Override protected void navigate() throws Exception { waitAndClickById("Demo-DemoLink", ""); waitAndClickByLinkText("Lookup with Stacked Results"); } protected void testLookUpStackedResults() throws InterruptedException { waitAndTypeByName(LOOKUP_CRITERIA_NUMBER_NAME, "a1"); waitAndClickButtonByText(SEARCH); waitForElementPresentByXpath("//a[contains(text(), 'a1')]"); waitAndClickButtonByText(CLEAR_VALUES); waitAndClickButtonByText(SEARCH); assertTextPresent(new String[]{"Travel Account Number: Required"}); waitAndClickButtonByText(CLEAR_VALUES); waitAndTypeByName(LOOKUP_CRITERIA_DATE, "234"); waitAndClickButtonByText(SEARCH); assertTextPresent(new String[]{ "Date Created: Must be a date in the following format(s): MM/dd/yy, MM/dd/yyyy, MM-dd-yy, MM-dd-yyyy, yyyy-MM-dd"}); } @Test public void testLookUpMultiValueBookmark() throws Exception { testLookUpStackedResults(); passed(); } @Test public void testLookUpMultiValueNav() throws Exception { testLookUpStackedResults(); passed(); } }
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/stackedresults/DemoLookUpStackedResultsAft.java
/** * Copyright 2005-2014 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.krad.demo.lookup.stackedresults; import org.junit.Test; import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase; import org.openqa.selenium.By; /** * This class performs simple tests on the stacked results lookup * * @author Kuali Rice Team ([email protected]) */ public class DemoLookUpStackedResultsAft extends WebDriverLegacyITBase { /** * /kr-krad/lookup?methodToCall=start&viewId=LookupSampleViewMultipleValuesSelectLimit&hideReturnLink=true */ public static final String BOOKMARK_URL = "/kr-krad/lookup?methodToCall=start&viewId=LookupSampleViewStackedResults&hideReturnLink=true"; /** * lookupCriteria[number] */ private static final String LOOKUP_CRITERIA_NUMBER_NAME="lookupCriteria[number]"; private static final String LOOKUP_CRITERIA_DATE="lookupCriteria[createDate]"; /** * Search */ private static final String SEARCH="Search"; /** * Clear Values */ private static final String CLEAR_VALUES="Clear Values"; @Override public String getBookmarkUrl() { return BOOKMARK_URL; } @Override protected void navigate() throws Exception { waitAndClickById("Demo-DemoLink", ""); waitAndClickByLinkText("Lookup Stacked Results"); } protected void testLookUpStackedResults() throws InterruptedException { waitAndTypeByName(LOOKUP_CRITERIA_NUMBER_NAME, "a1"); waitAndClickButtonByText(SEARCH); waitForElementPresentByXpath("//a[contains(text(), 'a1')]"); waitAndClickButtonByText(CLEAR_VALUES); waitAndClickButtonByText(SEARCH); assertTextPresent(new String[]{"Travel Account Number: Required"}); waitAndClickButtonByText(CLEAR_VALUES); waitAndTypeByName(LOOKUP_CRITERIA_DATE, "234"); waitAndClickButtonByText(SEARCH); assertTextPresent(new String[]{ "Date Created: Must be a date in the following format(s): MM/dd/yy, MM/dd/yyyy, MM-dd-yy, MM-dd-yyyy, yyyy-MM-dd"}); } // No Nav test, there is no link to this page @Test public void testLookUpMultiValueBookmark() throws Exception { testLookUpStackedResults(); passed(); } }
RICEQA-451 : Fill AFT Gap: KRAD Demo - Lookup with Stacked Results - link now exists, create nav test
rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/stackedresults/DemoLookUpStackedResultsAft.java
RICEQA-451 : Fill AFT Gap: KRAD Demo - Lookup with Stacked Results - link now exists, create nav test
<ide><path>ice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/lookup/stackedresults/DemoLookUpStackedResultsAft.java <ide> @Override <ide> protected void navigate() throws Exception { <ide> waitAndClickById("Demo-DemoLink", ""); <del> waitAndClickByLinkText("Lookup Stacked Results"); <add> waitAndClickByLinkText("Lookup with Stacked Results"); <ide> } <ide> <ide> protected void testLookUpStackedResults() throws InterruptedException { <ide> "Date Created: Must be a date in the following format(s): MM/dd/yy, MM/dd/yyyy, MM-dd-yy, MM-dd-yyyy, yyyy-MM-dd"}); <ide> } <ide> <del> // No Nav test, there is no link to this page <ide> @Test <ide> public void testLookUpMultiValueBookmark() throws Exception { <ide> testLookUpStackedResults(); <ide> passed(); <ide> } <add> <add> @Test <add> public void testLookUpMultiValueNav() throws Exception { <add> testLookUpStackedResults(); <add> passed(); <add> } <ide> }
JavaScript
mit
77d8afcbca373efc00f0b4c3d304bd73e65bd0c7
0
ollien/Spectabular,ollien/Spectabular
var unmovedPins = []; //Stores pinned tabs that haven't been within the popup var pinnedTabs = []; //Stores pinned tabs that have been moved within the popup var darkMode = true; //Gets windows from storage function getStorage(callback){ chrome.storage.local.get("windows",callback); } function getOptions(callback){ chrome.storage.local.get("options",callback); } function changeWindowName(windowId,newName,callback){ getStorage(function(data){ var windows = data.windows; var changedWindow = windows.filter(function(currentWindow){ return currentWindow.id===windowId; }); if (changedWindow.length===1){ changedWindow[0].name = newName; chrome.storage.local.set({"windows":windows},callback); chrome.runtime.sendMessage({'nameChange':{'windowId':windowId,'name':newName}}); } else{ throw "More than one window has the id "+windowId+". This should never happen." } }); } function getWindows(windowList,callback){ getStorage(function(data){ if (data!=null){ setupWindows(windowList,data.windows,callback); } else{ throw "Windows is null, this hsould never happen."; } }); } function setupWindows(windowList,windows,callback){ if (windows.length===0){ callback(); } else{ windows.forEach(function(currentWindow){ setupWindowElement(currentWindow, function(windowLi){ setupTabs(currentWindow.tabs, function(tabElements){ var tabsUl = windowLi.querySelector('ul.tabs'); tabElements.forEach(function(currentTab){ tabsUl.appendChild(currentTab); }); stripeTabs(tabsUl); windowList.appendChild(windowLi); callback(); }); }); }); } } //Sets up all tabs to be in their window elements function setupWindowElement(currentWindow,callback){ var li = document.createElement("li"); var ul = document.createElement("ul"); var textContent = document.createElement("span"); var overflowContainer = document.createElement("span"); var windowName = document.createElement("span"); var tabInfo = document.createElement("span"); var tabCount = document.createElement("span"); var tabWord = document.createElement("span"); li.classList.add("window"); li.classList.add("noselect"); ul.classList.add("tabs"); li.setAttribute("windowId", currentWindow.id); textContent.classList.add("textContent"); if (!darkMode){ textContent.classList.add("light"); } overflowContainer.classList.add("overflowContainer"); tabInfo.classList.add("tabInfo"); windowName.classList.add("windowName"); windowName.textContent = currentWindow.name; tabCount.classList.add("tabCount"); tabCount.textContent = currentWindow.tabs.length.toString(); tabWord.classList.add("tabWord"); tabWord.textContent = (currentWindow.tabs.length>1 ? " tabs":" tab"); windowName.addEventListener('dblclick', function(event){ var input = document.createElement('input'); input.setAttribute('value',windowName.textContent); input.addEventListener('keydown', function(event){ event.stopPropagation(); if(event.keyCode===13){ event.preventDefault(); var windowId = parseInt(input.parentNode.parentNode.getAttribute('windowId')); windowName.textContent = input.value; input.parentNode.replaceChild(windowName,input); changeWindowName(windowId, input.value); } }); windowName.parentNode.replaceChild(input,windowName); input.focus(); input.select(); }); tabInfo.appendChild(tabCount); tabInfo.appendChild(tabWord); overflowContainer.appendChild(windowName); overflowContainer.appendChild(tabInfo); textContent.appendChild(overflowContainer); li.appendChild(textContent); li.appendChild(ul); callback(li); } function setupTabs(tabs,callback){ var tabElements = []; tabs.forEach(function(currentTab){ //Workaround for null elements. not final. if (currentTab===null){ console.log("[DEBUG] NULL ELEMENT WAS FOUND. SKIPPING OVER."); return; } var li = document.createElement("li"); var textSpan = document.createElement("span"); var closeButton = document.createElement("i"); var pinButton = document.createElement("i"); li.setAttribute('tabId', currentTab.id); closeButton.classList.add("fa"); closeButton.classList.add("fa-remove"); closeButton.classList.add("close"); closeButton.classList.add("noselect"); closeButton.classList.add("pointer"); pinButton.classList.add("fa"); pinButton.classList.add("fa-thumb-tack"); pinButton.classList.add("pin"); pinButton.classList.add("noselect"); closeButton.classList.add("pointer"); if (currentTab.pinned){ pinButton.classList.add("pinned"); pinnedTabs.push(li); } li.classList.add("tab"); li.classList.add("noselect"); li.classList.add("pointer"); if (!darkMode){ li.classList.add("light"); } //Setup favicon if (currentTab.favIconUrl!==undefined && currentTab.favIconUrl!==null && currentTab.favIconUrl.indexOf("chrome://")===-1){ li.style.backgroundImage = "url(\'"+currentTab.favIconUrl+"\')"; } else{ li.style.backgroundImage = "url(\'img/default-favicon.png\')"; } li.setAttribute("tabUrl", currentTab.url); textSpan.classList.add("tabName"); textSpan.textContent=currentTab.title; if (textSpan.textContent==""){ textSpan.textContent="Untitled"; } closeButton.addEventListener('click',function(event){ event.preventDefault(); event.stopPropagation(); chrome.tabs.remove(currentTab.id); decrementTabCount(li.parentNode); if (li.parentNode.childNodes.length===1){ //If it's one this means we're removing the window. li.parentNode.parentNode.parentNode.removeChild(li.parentNode.parentNode); } else{ li.parentNode.removeChild(li); } setHeights(); }); pinButton.addEventListener('click',function(event){ event.preventDefault(); event.stopPropagation(); if (pinButton.classList.contains('pinned')){ pinButton.classList.remove("pinned"); chrome.tabs.update(currentTab.id, {'pinned':false}); } else{ pinButton.classList.add("pinned"); chrome.tabs.update(currentTab.id, {'pinned':true}); unmovedPins.push(li); } }); //Switches to the tab clicked li.addEventListener('click',function(event){ event.stopPropagation(); //If the mouse is clicked within the bounds of the closeButton, simulate a click event and return. if (event.pageX>=closeButton.getBoundingClientRect().left && event.pageX<=closeButton.getBoundingClientRect().right){ closeButton.click(); return; } //If the mouse is clicked within the bounds of the pinButton, simulate a click event and return. if (event.pageX>=pinButton.getBoundingClientRect().left && event.pageX<=pinButton.getBoundingClientRect().right){ pinButton.click(); return; } chrome.windows.getCurrent(function(resultWindow){ if (currentTab.id!=resultWindow.id){ chrome.windows.update(currentTab.windowId,{'focused':true}); } chrome.tabs.update(currentTab.id,{'highlighted':true,'active':true}); }); }); var mouseListenerFunction = function(event){ //If the mouse is within the bounds of the closeButton, highlight it as if it's being hovered. if (event.clientX>=closeButton.getBoundingClientRect().left && event.clientX<=closeButton.getBoundingClientRect().right){ closeButton.classList.add('fakeHover'); } else{ closeButton.classList.remove('fakeHover'); } //If the mouse is within the bounds of the pinButton, highlight it as if it's being hovered. if (event.clientX>=pinButton.getBoundingClientRect().left && event.clientX<=pinButton.getBoundingClientRect().right){ pinButton.classList.add('fakeHover'); } else{ pinButton.classList.remove('fakeHover'); } } li.addEventListener('mousein', mouseListenerFunction); li.addEventListener('mousemove', mouseListenerFunction); li.addEventListener('mouseout', function(event){ closeButton.classList.remove('fakeHover'); pinButton.classList.remove('fakeHover'); }); li.appendChild(textSpan); textSpan.appendChild(pinButton); textSpan.appendChild(closeButton); tabElements.push(li); }); callback(tabElements); } function decrementTabCount(tabsUl){ var li = tabsUl.parentNode; if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){ throw "Not a tabs ul"; } var tabCount = li.querySelector('span.tabInfo>span.tabCount'); var num = parseInt(tabCount.textContent)-1; tabCount.textContent=num.toString(); var windows = li.parentNode; if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){ throw "Not a tabs ul"; } if (num===1){ li.querySelector('span.tabInfo>span.tabWord').textContent = " tab" } setHeights(); } function setTabCount(tabsUl,num){ var li = tabsUl.parentNode; if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){ throw "Not a tabs ul"; } var tabCount = li.querySelector('span.tabInfo>span.tabCount'); tabCount.textContent=num.toString(); var windows = li.parentNode; if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){ throw "Not a tabs ul"; } if (num===1){ li.querySelector('span.tabInfo>span.tabWord').textContent = " tab" } setHeights(); } function stripeTabs(tabsUl){ var children = Array.prototype.slice.call(tabsUl.childNodes); var odd = true; children.forEach(function(child){ if (!child.classList.contains("filtered")){ if (odd){ child.classList.add("odd"); odd = false; } else{ child.classList.remove("odd"); odd = true; } } else{ child.classList.remove("odd"); } }); } function removeChildren(element){ Array.prototype.slice.call(element.childNodes).forEach(function(child){ element.removeChild(child); }); } function search(query,mainList,callback){ var noResults = document.getElementById("noResults"); var itemFound = false; //If no items are found, this will be trie and noResults will be displayed Array.prototype.slice.call(mainList.childNodes).forEach(function(currentWindow,i){ var tabList = createTabList(mainList, i, true); //This should never happen, but it's a just in case. if (tabList.length===0){ return false; } var tabUl = tabList[0].parentNode; var tabCount = 0; tabList.forEach(function(currentTab){ if (currentTab.textContent.toLowerCase().indexOf(query.toLowerCase())>-1 || new URL(currentTab.getAttribute("tabUrl")).hostname.indexOf(query)>-1){ currentTab.classList.remove('filtered'); tabCount+=1; } else{ currentTab.classList.add('filtered'); } }); if (tabCount===0){ currentWindow.classList.add('filtered'); } else{ currentWindow.classList.remove('filtered'); itemFound = true; } stripeTabs(tabUl); //This will setTabCount(tabUl, tabCount); }); if(!itemFound){ noResults.style.display = "block"; } else{ noResults.style.display = "none"; } callback(); } function createWindowList(mainList,includeFiltered){ var windowList = Array.prototype.slice.call(mainList.querySelectorAll('li.window')); if (includeFiltered){ return windowList; } else{ return windowList.filter(function(currentWindow){ return !currentWindow.classList.contains("filtered"); }); } } function createTabList(mainList,windowKeyIndex,includeFiltered,windowList){ if (windowList===undefined){ var windowList = createWindowList(mainList, includeFiltered); } var tabList = Array.prototype.slice.call(windowList[windowKeyIndex].querySelector('ul.tabs').childNodes); if (includeFiltered){ return tabList; } else{ return tabList.filter(function(currentTab){ return !currentTab.classList.contains("filtered"); }); } } function setHeights(){ var windows = document.getElementById("windows"); var body = document.querySelector("body"); var html = document.querySelector("html"); var filterInput = document.getElementById("search"); var noResults = document.getElementById("noResults"); var height = windows.offsetHeight+filterInput.offsetHeight; var style = getComputedStyle(windows); if (noResults.style.display!=="none" && getComputedStyle(noResults).display!=="none"){ html.style.height = filterInput.getBoundingClientRect().bottom+"px"; body.style.height = filterInput.getBoundingClientRect().bottom+"px"; } else{ if (style.marginTop.length>0){ height+=parseInt(style.marginTop); } if (style.marginBottom.length>0){ height+=parseInt(style.marginBottom); } if (height>=600){ height = 600; } height+="px"; html.style.height = height; body.style.height = height; } } document.addEventListener('DOMContentLoaded', function() { var mainList = document.getElementById("windows"); var filterInput = document.getElementById("search"); var windowKeyIndex = -1; //-1 indicdatesnothing is selected. ANything above that indicates that a window is selected var tabKeyIndex = -2; //-2 indicates nothing is selected. -1 indicates the window is selected. Anything above that indicates that a tab is selected. var shiftDown = false; getOptions(function(data){ darkMode = data.options.darkMode; getWindows(mainList,setHeights); }); filterInput.addEventListener('input', function(event){ search(filterInput.value,mainList,setHeights); }); //Workaround to prevent letters from triggering events. filterInput.addEventListener('keydown', function(event){ if (event.keyCode!=40 && event.keyCode!=38 && event.keyCode!=13 && event.keyCode!=33 && event.keyCode!=34){ event.stopPropagation(); } if (event.keyCode===16){ shiftDown = true; } }); chrome.tabs.onMoved.addListener(function(tabId,object){ if (!mainList.classList.contains('searching')){ var startPos = object.fromIndex; var endPos = object.toIndex; var pinnedTab = unmovedPins.filter(function(tab){ return parseInt(tab.getAttribute('tabId'))===tabId; }); if (pinnedTab.length===0){ pinnedTab = pinnedTabs.filter(function(tab){ return parseInt(tab.getAttribute('tabId'))===tabId; }); } if (pinnedTab.length===1){ pinnedTab = pinnedTab[0]; var ul = pinnedTab.parentNode; var children = Array.prototype.slice.call(ul.childNodes); var pinnedPos = unmovedPins.indexOf(pinnedTab); if (pinnedPos==-1){ pinnedPos = pinnedTabs.indexOf(pinnedTab); } var temp = children[startPos]; children.splice(startPos,1); children.splice(endPos, 0,temp); removeChildren(ul); children.forEach(function(child){ ul.appendChild(child); }); pinnedTabs.push(pinnedTab); unmovedPins.splice(pinnedPos,1); if (pinnedTab.classList.contains("keyHover")){ tabKeyIndex = endPos; } } else{ debugger; console.log(pinnedTab); } } }); window.addEventListener('keydown', function(event){ var windowList = createWindowList(mainList); var tabList = windowKeyIndex>=0 ? createTabList(mainList,windowKeyIndex) : null; //Track if shift is pressed if (event.keyCode===16){ shiftDown = true; } //If down is pressed, traverse through tabs. If page down is pressed, traverse through windows. else if (event.keyCode===40 || event.keyCode===34){ event.preventDefault(); event.stopPropagation(); if (document.activeElement===filterInput){ filterInput.blur(); } //If shift and down are pressed, or page down is pressed, traverse through windows if (shiftDown || event.keyCode===34){ if (windowKeyIndex<windowList.length-1){ if (windowKeyIndex>=0) windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0) tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex=-1; windowKeyIndex+=1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom>document.querySelector('body').clientHeight){ var scrollAmount = windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom - document.querySelector('body').clientHeight/2; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight); } } } //If nothing is selected, select the the window itself. else if (tabKeyIndex===-2){ if (windowKeyIndex>=0) windowList[windowKeyIndex].classList.remove('keyHover'); windowKeyIndex+=1; windowList[windowKeyIndex].classList.add('keyHover'); tabKeyIndex+=1; if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom<=0){ scrollTo(0, windowList[windowKeyIndex].getBoundingClientRect().top); } } //If we're at the last element, switch windows. else if (tabKeyIndex===tabList.length-1){ if (windowKeyIndex<windowList.length-1){ tabList[tabKeyIndex].classList.remove('keyHover'); windowKeyIndex+=1; tabKeyIndex = -1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom>=document.querySelector('body').clientHeight){ var scrollAmount = windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom - document.querySelector('body').clientHeight; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight); } else if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom<=0){ scrollTo(0, windowList[windowKeyIndex].getBoundingClientRect().bottom); } } } //Otherwise, just traverse the tab list. else if (tabKeyIndex<tabList.length-1){ windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0){ tabList[tabKeyIndex].classList.remove('keyHover'); } tabKeyIndex+=1; tabList[tabKeyIndex].classList.add('keyHover'); } //Scroll if the index passes the bottom border if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom>document.querySelector('body').clientHeight){ //Get the amount less than the height that the element is var scrollAmount = tabList[tabKeyIndex].getBoundingClientRect().bottom - document.querySelector('body').clientHeight; //Scroll by either the height or scrollAmount, whichever is greater. scrollBy(0,scrollAmount>tabList[tabKeyIndex].clientHeight ? scrollAmount : tabList[tabKeyIndex].clientHeight); } //If the user has scrolled off screen, but down is pressed, scroll to it. else if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom<=0){ scrollTo(0, tabList[tabKeyIndex].getBoundingClientRect().bottom); } } //If up is pressed, traverse through tabs else if (event.keyCode===38 || event.keyCode===33 ){ event.preventDefault(); event.stopPropagation(); //If shift is down, or page up is pressed, traverse windows if (shiftDown || event.keyCode===33){ if (windowKeyIndex>0){ windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0) tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex=-1; windowKeyIndex-=1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().top<=0){ var scrollAmount = document.querySelector('body').clientHeight/2 -windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount*-1 : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight*-1); } } } //If a window is selected, switch to the next one. else if (tabKeyIndex===-1){ windowList[windowKeyIndex].classList.remove('keyHover'); if (windowKeyIndex>0){ windowKeyIndex-=1; tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex = tabList.length-1; tabList[tabKeyIndex].classList.add('keyHover'); } //If it's the first window, highlight the search bar else{ windowKeyIndex = -1; tabKeyIndex = -2; filterInput.focus(); } } //If we're at the top of a tab list, highlight the window itself. else if (tabKeyIndex===0){ tabList[tabKeyIndex].classList.remove('keyHover'); windowList[windowKeyIndex].classList.add('keyHover'); tabKeyIndex-=1; } //In all other instances, just move up one. else if (tabKeyIndex>0){ windowList[windowKeyIndex].classList.remove('keyHover'); tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex-=1; tabList[tabKeyIndex].classList.add('keyHover'); } //Scroll if the tab index passes the top border. if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().top<=0){ scrollBy(0, tabList[tabKeyIndex].getBoundingClientRect().top); } //If the user has scrolled off screen, but up is pressed, scroll to it. else if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom>=document.querySelector('body').clientHeight){ //Get the amount less than the height that the element is var scrollAmount = tabList[tabKeyIndex].getBoundingClientRect().bottom - document.querySelector('body').clientHeight; //Scroll by either the height or scrollAmount, whichever is greater. scrollBy(0,scrollAmount>tabList[tabKeyIndex].clientHeight ? scrollAmount : tabList[tabKeyIndex].clientHeight); } //If switching windows, scroll by the amount that the window is off the screen. else if (tabKeyIndex===-1 && windowList[windowKeyIndex].getBoundingClientRect().top<=0){ scrollBy(0, windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().top); } } //If enter is pressed, switch to the tab. else if (event.keyCode===13){ if (tabKeyIndex>=0){ tabList[tabKeyIndex].click(); } else if (mainList.classList.contains('searching') && tabKeyIndex===-2){ createTabList(mainList, 0)[0].click(); } } //Close when c is pressed else if (event.keyCode===67){ if (tabKeyIndex>=0){ //If shift is down, close all except the selected window if (shiftDown){ //Get all tabs in the current window var closeTabList = createTabList(mainList, windowKeyIndex, true, windowList); var selectedTab = tabList[tabKeyIndex]; closeTabList.forEach(function(tab){ if (tab!==selectedTab){ tab.querySelector('i.close').click(); } }); //Set the tab count to 1 to prevent negative numbers setTabCount(selectedTab.parentNode, 1); tabKeyIndex = 0; } else{ tabList[tabKeyIndex].querySelector('i.close').click(); //Move the selection after pressing c. //Check to make sure we're not leaving the bounds of the list if (tabKeyIndex-1>0){ tabKeyIndex-=1; } //If we're closing a window with only one tab left, move to the previous list. if (tabList.length===0){ //Remove the list from the popup //If we're at the front of the list, we move to the window below it. if (windowKeyIndex===0){ tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex=0; } //Otherwise, we move up one. if (windowKeyIndex>0){ windowKeyIndex-=1; tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex=tabList.length-1; } } tabList[tabKeyIndex].classList.add('keyHover'); } } } //Pin when p is pressed else if(event.keyCode===80){ if (tabKeyIndex>=0){ tabList[tabKeyIndex].querySelector('i.pin').click(); } } //Go to search box when s is pressed. else if (event.keyCode===83){ event.preventDefault(); scrollTo(0, 0); filterInput.focus(); } //Rename a window when R is pressed else if (event.keyCode===82){ event.preventDefault(); if (tabKeyIndex===-1){ var windowList = createWindowList(mainList); windowList[windowKeyIndex].querySelector('span.textContent > span.windowName').dispatchEvent(new MouseEvent('dblclick',{ 'view':window, 'bubbles':true, 'cancellable':true })); } } }); window.addEventListener('keyup', function(event){ //Track if shift is released if (event.keyCode===16){ shiftDown = false; } }); filterInput.addEventListener('focus', function(event){ var windowList = createWindowList(mainList); windowList.forEach(function(currentWindow,i){ currentWindow.classList.remove('keyHover'); var tabList = createTabList(mainList, i); tabList.forEach(function(currentTab){ currentTab.classList.remove('keyHover'); }); }); windowKeyIndex = -1; tabKeyIndex = -2; }); });
popup.js
var unmovedPins = []; //Stores pinned tabs that haven't been within the popup var pinnedTabs = []; //Stores pinned tabs that have been moved within the popup var darkMode = true; //Gets windows from storage function getStorage(callback){ chrome.storage.local.get("windows",callback); } function getOptions(callback){ chrome.storage.local.get("options",callback); } function changeWindowName(windowId,newName,callback){ getStorage(function(data){ var windows = data.windows; var changedWindow = windows.filter(function(currentWindow){ return currentWindow.id===windowId; }); if (changedWindow.length===1){ changedWindow[0].name = newName; chrome.storage.local.set({"windows":windows},callback); chrome.runtime.sendMessage({'nameChange':{'windowId':windowId,'name':newName}}); } else{ throw "More than one window has the id "+windowId+". This should never happen." } }); } function getWindows(windowList,callback){ getStorage(function(data){ if (data!=null){ setupWindows(windowList,data.windows,callback); } else{ throw "Windows is null, this hsould never happen."; } }); } function setupWindows(windowList,windows,callback){ if (windows.length===0){ callback(); } else{ windows.forEach(function(currentWindow){ setupWindowElement(currentWindow, function(windowLi){ setupTabs(currentWindow.tabs, function(tabElements){ var tabsUl = windowLi.querySelector('ul.tabs'); tabElements.forEach(function(currentTab){ tabsUl.appendChild(currentTab); }); stripeTabs(tabsUl); windowList.appendChild(windowLi); callback(); }); }); }); } } //Sets up all tabs to be in their window elements function setupWindowElement(currentWindow,callback){ var li = document.createElement("li"); var ul = document.createElement("ul"); var textContent = document.createElement("span"); var overflowContainer = document.createElement("span"); var windowName = document.createElement("span"); var tabInfo = document.createElement("span"); var tabCount = document.createElement("span"); var tabWord = document.createElement("span"); li.classList.add("window"); li.classList.add("noselect"); ul.classList.add("tabs"); li.setAttribute("windowId", currentWindow.id); textContent.classList.add("textContent"); if (!darkMode){ textContent.classList.add("light"); } overflowContainer.classList.add("overflowContainer"); tabInfo.classList.add("tabInfo"); windowName.classList.add("windowName"); windowName.textContent = currentWindow.name; tabCount.classList.add("tabCount"); tabCount.textContent = currentWindow.tabs.length.toString(); tabWord.classList.add("tabWord"); tabWord.textContent = (currentWindow.tabs.length>1 ? " tabs":" tab"); windowName.addEventListener('dblclick', function(event){ var input = document.createElement('input'); input.setAttribute('value',windowName.textContent); input.addEventListener('keydown', function(event){ event.stopPropagation(); if(event.keyCode===13){ event.preventDefault(); var windowId = parseInt(input.parentNode.parentNode.getAttribute('windowId')); windowName.textContent = input.value; input.parentNode.replaceChild(windowName,input); changeWindowName(windowId, input.value); } }); windowName.parentNode.replaceChild(input,windowName); input.focus(); input.select(); }); tabInfo.appendChild(tabCount); tabInfo.appendChild(tabWord); overflowContainer.appendChild(windowName); overflowContainer.appendChild(tabInfo); textContent.appendChild(overflowContainer); li.appendChild(textContent); li.appendChild(ul); callback(li); } function setupTabs(tabs,callback){ var tabElements = []; tabs.forEach(function(currentTab){ //Workaround for null elements. not final. if (currentTab===null){ console.log("[DEBUG] NULL ELEMENT WAS FOUND. SKIPPING OVER."); return; } var li = document.createElement("li"); var textSpan = document.createElement("span"); var closeButton = document.createElement("i"); var pinButton = document.createElement("i"); li.setAttribute('tabId', currentTab.id); closeButton.classList.add("fa"); closeButton.classList.add("fa-remove"); closeButton.classList.add("close"); closeButton.classList.add("noselect"); closeButton.classList.add("pointer"); pinButton.classList.add("fa"); pinButton.classList.add("fa-thumb-tack"); pinButton.classList.add("pin"); pinButton.classList.add("noselect"); closeButton.classList.add("pointer"); if (currentTab.pinned){ pinButton.classList.add("pinned"); pinnedTabs.push(li); } li.classList.add("tab"); li.classList.add("noselect"); li.classList.add("pointer"); if (!darkMode){ li.classList.add("light"); } //Setup favicon if (currentTab.favIconUrl!==undefined && currentTab.favIconUrl!==null && currentTab.favIconUrl.indexOf("chrome://")===-1){ li.style.backgroundImage = "url(\'"+currentTab.favIconUrl+"\')"; } else{ li.style.backgroundImage = "url(\'img/default-favicon.png\')"; } li.setAttribute("tabUrl", currentTab.url); textSpan.classList.add("tabName"); textSpan.textContent=currentTab.title; if (textSpan.textContent==""){ textSpan.textContent="Untitled"; } closeButton.addEventListener('click',function(event){ event.preventDefault(); event.stopPropagation(); chrome.tabs.remove(currentTab.id); decrementTabCount(li.parentNode); if (li.parentNode.childNodes.length===1){ //If it's one this means we're removing the window. li.parentNode.parentNode.parentNode.removeChild(li.parentNode.parentNode); } else{ li.parentNode.removeChild(li); } setHeights(); }); pinButton.addEventListener('click',function(event){ event.preventDefault(); event.stopPropagation(); if (pinButton.classList.contains('pinned')){ pinButton.classList.remove("pinned"); chrome.tabs.update(currentTab.id, {'pinned':false}); } else{ pinButton.classList.add("pinned"); chrome.tabs.update(currentTab.id, {'pinned':true}); unmovedPins.push(li); } }); //Switches to the tab clicked li.addEventListener('click',function(event){ event.stopPropagation(); //If the mouse is clicked within the bounds of the closeButton, simulate a click event and return. if (event.pageX>=closeButton.getBoundingClientRect().left && event.pageX<=closeButton.getBoundingClientRect().right){ closeButton.click(); return; } //If the mouse is clicked within the bounds of the pinButton, simulate a click event and return. if (event.pageX>=pinButton.getBoundingClientRect().left && event.pageX<=pinButton.getBoundingClientRect().right){ pinButton.click(); return; } chrome.windows.getCurrent(function(resultWindow){ if (currentTab.id!=resultWindow.id){ chrome.windows.update(currentTab.windowId,{'focused':true}); } chrome.tabs.update(currentTab.id,{'highlighted':true,'active':true}); }); }); var mouseListenerFunction = function(event){ //If the mouse is within the bounds of the closeButton, highlight it as if it's being hovered. if (event.clientX>=closeButton.getBoundingClientRect().left && event.clientX<=closeButton.getBoundingClientRect().right){ closeButton.classList.add('fakeHover'); } else{ closeButton.classList.remove('fakeHover'); } //If the mouse is within the bounds of the pinButton, highlight it as if it's being hovered. if (event.clientX>=pinButton.getBoundingClientRect().left && event.clientX<=pinButton.getBoundingClientRect().right){ pinButton.classList.add('fakeHover'); } else{ pinButton.classList.remove('fakeHover'); } } li.addEventListener('mousein', mouseListenerFunction); li.addEventListener('mousemove', mouseListenerFunction); li.addEventListener('mouseout', function(event){ closeButton.classList.remove('fakeHover'); pinButton.classList.remove('fakeHover'); }); li.appendChild(textSpan); textSpan.appendChild(pinButton); textSpan.appendChild(closeButton); tabElements.push(li); }); callback(tabElements); } function decrementTabCount(tabsUl){ var li = tabsUl.parentNode; if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){ throw "Not a tabs ul"; } var tabCount = li.querySelector('span.tabInfo>span.tabCount'); var num = parseInt(tabCount.textContent)-1; tabCount.textContent=num.toString(); var windows = li.parentNode; if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){ throw "Not a tabs ul"; } if (num===1){ li.querySelector('span.tabInfo>span.tabWord').textContent = " tab" } setHeights(); } function setTabCount(tabsUl,num){ var li = tabsUl.parentNode; if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){ throw "Not a tabs ul"; } var tabCount = li.querySelector('span.tabInfo>span.tabCount'); tabCount.textContent=num.toString(); var windows = li.parentNode; if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){ throw "Not a tabs ul"; } if (num===1){ li.querySelector('span.tabInfo>span.tabWord').textContent = " tab" } setHeights(); } function stripeTabs(tabsUl){ var children = Array.prototype.slice.call(tabsUl.childNodes); var odd = true; children.forEach(function(child){ if (!child.classList.contains("filtered")){ if (odd){ child.classList.add("odd"); odd = false; } else{ child.classList.remove("odd"); odd = true; } } else{ child.classList.remove("odd"); } }); } function removeChildren(element){ Array.prototype.slice.call(element.childNodes).forEach(function(child){ element.removeChild(child); }); } function search(query,mainList,callback){ var noResults = document.getElementById("noResults"); var itemFound = false; //If no items are found, this will be trie and noResults will be displayed Array.prototype.slice.call(mainList.childNodes).forEach(function(currentWindow,i){ var tabList = createTabList(mainList, i, true); //This should never happen, but it's a just in case. if (tabList.length===0){ return false; } var tabUl = tabList[0].parentNode; var tabCount = 0; tabList.forEach(function(currentTab){ if (currentTab.textContent.toLowerCase().indexOf(query.toLowerCase())>-1 || new URL(currentTab.getAttribute("tabUrl")).hostname.indexOf(query)>-1){ currentTab.classList.remove('filtered'); tabCount+=1; } else{ currentTab.classList.add('filtered'); } }); if (tabCount===0){ currentWindow.classList.add('filtered'); } else{ currentWindow.classList.remove('filtered'); itemFound = true; } stripeTabs(tabUl); //This will setTabCount(tabUl, tabCount); }); if(!itemFound){ noResults.style.display = "block"; } else{ noResults.style.display = "none"; } callback(); } function createWindowList(mainList,includeFiltered){ var windowList = Array.prototype.slice.call(mainList.querySelectorAll('li.window')); if (includeFiltered){ return windowList; } else{ return windowList.filter(function(currentWindow){ return !currentWindow.classList.contains("filtered"); }); } } function createTabList(mainList,windowKeyIndex,includeFiltered,windowList){ if (windowList===undefined){ var windowList = createWindowList(mainList, includeFiltered); } var tabList = Array.prototype.slice.call(windowList[windowKeyIndex].querySelector('ul.tabs').childNodes); if (includeFiltered){ return tabList; } else{ return tabList.filter(function(currentTab){ return !currentTab.classList.contains("filtered"); }); } } function setHeights(){ var windows = document.getElementById("windows"); var body = document.querySelector("body"); var html = document.querySelector("html"); var filterInput = document.getElementById("search"); var noResults = document.getElementById("noResults"); var height = windows.offsetHeight+filterInput.offsetHeight; var style = getComputedStyle(windows); if (noResults.style.display!=="none" && getComputedStyle(noResults).display!=="none"){ html.style.height = filterInput.getBoundingClientRect().bottom+"px"; body.style.height = filterInput.getBoundingClientRect().bottom+"px"; } else{ if (style.marginTop.length>0){ height+=parseInt(style.marginTop); } if (style.marginBottom.length>0){ height+=parseInt(style.marginBottom); } if (height>=600){ height = 600; } height+="px"; html.style.height = height; body.style.height = height; } } document.addEventListener('DOMContentLoaded', function() { var mainList = document.getElementById("windows"); var filterInput = document.getElementById("search"); var windowKeyIndex = -1; //-1 indicdatesnothing is selected. ANything above that indicates that a window is selected var tabKeyIndex = -2; //-2 indicates nothing is selected. -1 indicates the window is selected. Anything above that indicates that a tab is selected. var shiftDown = false; getOptions(function(data){ darkMode = data.options.darkMode; getWindows(mainList,setHeights); }); filterInput.addEventListener('input', function(event){ search(filterInput.value,mainList,setHeights); }); //Workaround to prevent letters from triggering events. filterInput.addEventListener('keydown', function(event){ if (event.keyCode!=40 && event.keyCode!=38 && event.keyCode!=13 && event.keyCode!=33 && event.keyCode!=34){ event.stopPropagation(); } if (event.keyCode===16){ shiftDown = true; } }); chrome.tabs.onMoved.addListener(function(tabId,object){ if (!mainList.classList.contains('searching')){ var startPos = object.fromIndex; var endPos = object.toIndex; var pinnedTab = unmovedPins.filter(function(tab){ return parseInt(tab.getAttribute('tabId'))===tabId; }); if (pinnedTab.length===0){ pinnedTab = pinnedTabs.filter(function(tab){ return parseInt(tab.getAttribute('tabId'))===tabId; }); } if (pinnedTab.length===1){ pinnedTab = pinnedTab[0]; var ul = pinnedTab.parentNode; var children = Array.prototype.slice.call(ul.childNodes); var pinnedPos = unmovedPins.indexOf(pinnedTab); if (pinnedPos==-1){ pinnedPos = pinnedTabs.indexOf(pinnedTab); } var temp = children[startPos]; children.splice(startPos,1); children.splice(endPos, 0,temp); removeChildren(ul); children.forEach(function(child){ ul.appendChild(child); }); pinnedTabs.push(pinnedTab); unmovedPins.splice(pinnedPos,1); if (pinnedTab.classList.contains("keyHover")){ tabKeyIndex = endPos; } } else{ debugger; console.log(pinnedTab); } } }); window.addEventListener('keydown', function(event){ var windowList = createWindowList(mainList); var tabList = windowKeyIndex>=0 ? createTabList(mainList,windowKeyIndex) : null; //Track if shift is pressed if (event.keyCode===16){ shiftDown = true; } //If down is pressed, traverse through tabs. If page down is pressed, traverse through windows. else if (event.keyCode===40 || event.keyCode===34){ event.preventDefault(); event.stopPropagation(); if (document.activeElement===filterInput){ filterInput.blur(); } //If shift and down are pressed, or page down is pressed, traverse through windows if (shiftDown || event.keyCode===34){ if (windowKeyIndex<windowList.length-1){ if (windowKeyIndex>=0) windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0) tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex=-1; windowKeyIndex+=1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom>document.querySelector('body').clientHeight){ var scrollAmount = windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom - document.querySelector('body').clientHeight/2; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight); } } } //If nothing is selected, select the the window itself. else if (tabKeyIndex===-2){ if (windowKeyIndex>=0) windowList[windowKeyIndex].classList.remove('keyHover'); windowKeyIndex+=1; windowList[windowKeyIndex].classList.add('keyHover'); tabKeyIndex+=1; if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom<=0){ scrollTo(0, windowList[windowKeyIndex].getBoundingClientRect().top); } } //If we're at the last element, switch windows. else if (tabKeyIndex===tabList.length-1){ if (windowKeyIndex<windowList.length-1){ tabList[tabKeyIndex].classList.remove('keyHover'); windowKeyIndex+=1; tabKeyIndex = -1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom>=document.querySelector('body').clientHeight){ var scrollAmount = windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom - document.querySelector('body').clientHeight; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight); } else if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom<=0){ scrollTo(0, windowList[windowKeyIndex].getBoundingClientRect().bottom); } } } //Otherwise, just traverse the tab list. else if (tabKeyIndex<tabList.length-1){ windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0){ tabList[tabKeyIndex].classList.remove('keyHover'); } tabKeyIndex+=1; tabList[tabKeyIndex].classList.add('keyHover'); } //Scroll if the index passes the bottom border if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom>document.querySelector('body').clientHeight){ //Get the amount less than the height that the element is var scrollAmount = tabList[tabKeyIndex].getBoundingClientRect().bottom - document.querySelector('body').clientHeight; //Scroll by either the height or scrollAmount, whichever is greater. scrollBy(0,scrollAmount>tabList[tabKeyIndex].clientHeight ? scrollAmount : tabList[tabKeyIndex].clientHeight); } //If the user has scrolled off screen, but down is pressed, scroll to it. else if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom<=0){ scrollTo(0, tabList[tabKeyIndex].getBoundingClientRect().bottom); } } //If up is pressed, traverse through tabs else if (event.keyCode===38 || event.keyCode===33 ){ event.preventDefault(); event.stopPropagation(); //If shift is down, or page up is pressed, traverse windows if (shiftDown || event.keyCode===33){ if (windowKeyIndex>0){ windowList[windowKeyIndex].classList.remove('keyHover'); if (tabKeyIndex>=0) tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex=-1; windowKeyIndex-=1; windowList[windowKeyIndex].classList.add('keyHover'); if (windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().top<=0){ var scrollAmount = document.querySelector('body').clientHeight/2 -windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().bottom; scrollBy(0,scrollAmount>windowList[windowKeyIndex].querySelector('span.textContent').clientHeight ? scrollAmount*-1 : windowList[windowKeyIndex].querySelector('span.textContent').clientHeight*-1); } } } //If a window is selected, switch to the next one. else if (tabKeyIndex===-1){ windowList[windowKeyIndex].classList.remove('keyHover'); if (windowKeyIndex>0){ windowKeyIndex-=1; tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex = tabList.length-1; tabList[tabKeyIndex].classList.add('keyHover'); } //If it's the first window, highlight the search bar else{ windowKeyIndex = -1; tabKeyIndex = -2; filterInput.focus(); } } //If we're at the top of a tab list, highlight the window itself. else if (tabKeyIndex===0){ tabList[tabKeyIndex].classList.remove('keyHover'); windowList[windowKeyIndex].classList.add('keyHover'); tabKeyIndex-=1; } //In all other instances, just move up one. else if (tabKeyIndex>0){ windowList[windowKeyIndex].classList.remove('keyHover'); tabList[tabKeyIndex].classList.remove('keyHover'); tabKeyIndex-=1; tabList[tabKeyIndex].classList.add('keyHover'); } //Scroll if the tab index passes the top border. if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().top<=0){ scrollBy(0, tabList[tabKeyIndex].getBoundingClientRect().top); } //If the user has scrolled off screen, but up is pressed, scroll to it. else if (tabKeyIndex>=0 && tabList[tabKeyIndex].getBoundingClientRect().bottom>=document.querySelector('body').clientHeight){ //Get the amount less than the height that the element is var scrollAmount = tabList[tabKeyIndex].getBoundingClientRect().bottom - document.querySelector('body').clientHeight; //Scroll by either the height or scrollAmount, whichever is greater. scrollBy(0,scrollAmount>tabList[tabKeyIndex].clientHeight ? scrollAmount : tabList[tabKeyIndex].clientHeight); } //If switching windows, scroll by the amount that the window is off the screen. else if (tabKeyIndex===-1 && windowList[windowKeyIndex].getBoundingClientRect().top<=0){ scrollBy(0, windowList[windowKeyIndex].querySelector('span.textContent').getBoundingClientRect().top); } } //If enter is pressed, switch to the tab. else if (event.keyCode===13){ if (tabKeyIndex>=0){ tabList[tabKeyIndex].click(); } else if (mainList.classList.contains('searching') && tabKeyIndex===-2){ createTabList(mainList, 0)[0].click(); } } //Close when c is pressed else if (event.keyCode===67){ if (tabKeyIndex>=0){ //If shift is down, close all except the selected window if (shiftDown){ //Get all tabs in the current window var closeTabList = createTabList(mainList, windowKeyIndex, true, windowList); var selectedTab = tabList[tabKeyIndex]; closeTabList.forEach(function(tab){ if (tab!==selectedTab){ tab.querySelector('i.close').click(); } }); //Set the tab count to 1 to prevent negative numbers setTabCount(selectedTab.parentNode, 1); tabKeyIndex = 0; } else{ tabList[tabKeyIndex].querySelector('i.close').click(); //Move the selection after pressing c. //Check to make sure we're not leaving the bounds of the list if (tabKeyIndex-1>0){ tabKeyIndex-=1; } //If we're closing a window with only one tab left, move to the previous list. if (tabList.length===1){ //Remove the list from the popup //If we're at the front of the list, we move to the window below it. if (windowKeyIndex===0){ tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex=0; } //Otherwise, we move up one. if (windowKeyIndex>0){ windowKeyIndex-=1; tabList = createTabList(mainList, windowKeyIndex); tabKeyIndex=tabList.length-1; } } tabList[tabKeyIndex].classList.add('keyHover'); } } } //Pin when p is pressed else if(event.keyCode===80){ if (tabKeyIndex>=0){ tabList[tabKeyIndex].querySelector('i.pin').click(); } } //Go to search box when s is pressed. else if (event.keyCode===83){ event.preventDefault(); scrollTo(0, 0); filterInput.focus(); } //Rename a window when R is pressed else if (event.keyCode===82){ event.preventDefault(); if (tabKeyIndex===-1){ var windowList = createWindowList(mainList); windowList[windowKeyIndex].querySelector('span.textContent > span.windowName').dispatchEvent(new MouseEvent('dblclick',{ 'view':window, 'bubbles':true, 'cancellable':true })); } } }); window.addEventListener('keyup', function(event){ //Track if shift is released if (event.keyCode===16){ shiftDown = false; } }); filterInput.addEventListener('focus', function(event){ var windowList = createWindowList(mainList); windowList.forEach(function(currentWindow,i){ currentWindow.classList.remove('keyHover'); var tabList = createTabList(mainList, i); tabList.forEach(function(currentTab){ currentTab.classList.remove('keyHover'); }); }); windowKeyIndex = -1; tabKeyIndex = -2; }); });
Revert "Fix bug where changing tabKeyIndex on winodw close wouldn't work, resolves #22" This reverts commit 3cf8eaaf2cec2614eacfac35af19bbef4a5f94fd.
popup.js
Revert "Fix bug where changing tabKeyIndex on winodw close wouldn't work, resolves #22"
<ide><path>opup.js <ide> tabKeyIndex-=1; <ide> } <ide> //If we're closing a window with only one tab left, move to the previous list. <del> if (tabList.length===1){ <add> if (tabList.length===0){ <ide> //Remove the list from the popup <ide> //If we're at the front of the list, we move to the window below it. <ide> if (windowKeyIndex===0){