def run(core, actor, target, commandString): if actor.getCombatFlag() > 0: return cell = actor.getContainer() building = actor.getGrandparent() ghost = actor.getSlottedObject('ghost') if not ghost or not cell or not building or not core.housingService.getPermissions( actor, cell): return if ghost.getAmountOfVendors() >= actor.getSkillModBase('manage_vendor'): actor.sendSystemMessage('@player_structure:full_vendors', 0) return suiOptions = HashMap() suiOptions.put(Long(1), '@player_structure:terminal') suiOptions.put(Long(2), '@player_structure:droid') # TODO add creatures window = core.suiService.createListBox(ListBoxType.LIST_BOX_OK_CANCEL, '@player_structure:vendor_type_t', '@player_structure:vendor_type_d', suiOptions, actor, None, 5) returnList = Vector() returnList.add('List.lstList:SelectedRow') window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, handleFirstWindow) core.suiService.openSUIWindow(window) return
def update(self, ss, when): strLine = Long.toString(when.getTimeInMillis()).encode('utf-8') if 'X' in ss: strLine = strLine + ',' \ + Double.toString(market.getLastPrice(0,'X-OPEN'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'X-HIGH'))\ .encode('utf-8') + ',' \ + Double.toString(market.getLastPrice(0,'X-LOW'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'X-CLOSE'))\ .encode('utf-8') + ','\ + Long.toString(market.getLastVolume(0,'X'))\ .encode('utf-8') else: strLine = strLine + ',-,-,-,-,-' if 'Y' in ss: strLine = strLine + ',' \ + Double.toString(market.getLastPrice(0,'Y-OPEN'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'Y-HIGH'))\ .encode('utf-8') + ',' \ + Double.toString(market.getLastPrice(0,'Y-LOW'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'Y-CLOSE'))\ .encode('utf-8') + ','\ + Long.toString(market.getLastVolume(0,'Y'))\ .encode('utf-8') else: strLine = strLine + ',-,-,-,-,-' print strLine
def update(self, ss, when): strLine = Long.toString(when.getTimeInMillis()).encode('utf-8') for s in bricSymbols: if s in ss: strLine = strLine + ',' \ + Double.toString(market.getLastPrice(0,s+'-OPEN'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,s+'-HIGH'))\ .encode('utf-8') + ',' \ + Double.toString(market.getLastPrice(0,s+'-LOW'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,s+'-CLOSE'))\ .encode('utf-8') + ','\ + Long.toString(market.getLastVolume(0,s))\ .encode('utf-8') else: strLine = strLine + ',-,-,-,-,-' if 'XAG' in ss: strLine = strLine + ',' \ + Double.toString(market.getLastPrice(0,'XAG-OPEN'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'XAG-HIGH'))\ .encode('utf-8') + ',' \ + Double.toString(market.getLastPrice(0,'XAG-LOW'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'XAG-CLOSE'))\ .encode('utf-8') + ','\ + Long.toString(market.getLastVolume(0,'XAG'))\ .encode('utf-8') else: strLine = strLine + ',-,-,-,-,-' print strLine
def makeUserOSH(hostCmdbId, userName, desc, uid, gid, homeDir): 'host OSH, str, str, str, str, str -> OSH vector' iuid = -1 igid = -1 try: iuid = Long(uid) except: iuid = -1 try: igid = Long(gid) except: igid = -1 myVec = ObjectStateHolderVector() u_obj = ObjectStateHolder('osuser') host_objSH = modeling.createOshByCmdbIdString('host', hostCmdbId) u_obj.setContainer(host_objSH) u_obj.setAttribute('data_name', userName) if (len(uid) > 0): u_obj.setAttribute('user_id', Long(iuid)) if (len(gid) > 0): u_obj.setAttribute('group_id', Long(igid)) if (len(desc) > 0): u_obj.setAttribute('data_note', desc) if (len(homeDir) > 0): u_obj.setAttribute('homedir', homeDir) myVec.add(u_obj) return (myVec)
def get_values(self): i = Integer(-5) pi = i.intValue() j = Long(5001) pj = j.longValue() d = Double(10.001) pd = d.doubleValue() return i, pi, j, pj, d, pd
def handleSelection(core, owner, target, option): if not target.getAttachment('vendorOwner') == owner.getObjectID(): return if target.getAttachment('initialized') == False: if option == 118: owner.sendSystemMessage('@player_structure:vendor_initialized', 0) target.setAttachment('initialized', True) core.bazaarService.startVendorUpdateTask(owner, target) else: if option == 118: suiOptions = HashMap() suiOptions.put(Long(1), 'Owner: ' + owner.getCustomName()) suiOptions.put( Long(2), 'Maintenance Pool: ' + str(target.getAttachment('maintenanceAmount')) + ' cr') maintenanceRate = 15 if target.getAttachment('onMap') is True: maintenanceRate += 6 suiOptions.put( Long(3), 'Maintenance Rate: ' + str(maintenanceRate) + ' cr/hr') suiOptions.put( Long(4), 'Number of Items For Sale: ' + str( core.bazaarService.getNumberOfItemsForSale( target.getObjectID()))) window = core.suiService.createListBox( ListBoxType.LIST_BOX_OK_CANCEL, '@player_structure:vendor_status', 'Vendor Status', suiOptions, owner, None, 5) core.suiService.openSUIWindow(window) if option == 205: target.setAttachment('vendorSearchEnabled', True) owner.sendSystemMessage('@player_structure:vendor_search_enabled', 0) if option == 206: target.setAttachment('vendorSearchEnabled', False) owner.sendSystemMessage('@player_structure:vendor_search_disabled', 0) if option == 217: window = core.suiService.createInputBox( InputBoxType.INPUT_BOX_OK_CANCEL, '@player_structure:pay_vendor_t', '@player_structure:pay_vendor_d', owner, target, 5, handlePayMaintenance) core.suiService.openSUIWindow(window) if option == 115: window = core.suiService.createInputBox( InputBoxType.INPUT_BOX_OK_CANCEL, '@player_structure:withdraw_vendor_t', '@player_structure:withdraw_vendor_d', owner, target, 5, handleWithdrawMaintenance) core.suiService.openSUIWindow(window) return
def test_nonzero(self): i, pi, j, pj, d, pd = self.get_values() self.assertEqual(bool(i), bool(pi)) self.assertEqual(bool(j), bool(pj)) self.assertEqual(bool(d), bool(pd)) self.assertFalse(bool(Integer(0))) self.assertFalse(bool(Long(0))) self.assertFalse(bool(Double(0.0))) self.assertTrue(bool(Integer(1))) self.assertTrue(bool(Long(1))) self.assertTrue(bool(Double(1.0)))
def handleFirstWindow(actor, window, eventType, returnList): core = NGECore.getInstance() index = int(returnList.get(0)) selected = window.getObjectIdByIndex(index) hiring = actor.getSkillModBase('hiring') if selected == 1: suiOptions = HashMap() if hiring >= 10: suiOptions.put(Long(1), '@player_structure:terminal_bulky') if hiring >= 30: suiOptions.put(Long(2), '@player_structure:terminal_standard') if hiring >= 50: suiOptions.put(Long(3), '@player_structure:terminal_small') if hiring >= 75: suiOptions.put(Long(4), '@player_structure:terminal_fancy') if hiring >= 90: suiOptions.put(Long(5), '@player_structure:terminal_slim') window = core.suiService.createListBox( ListBoxType.LIST_BOX_OK_CANCEL, '@player_structure:terminal_type_t', '@player_structure:terminal_type_d', suiOptions, actor, None, 5) returnList = Vector() returnList.add('List.lstList:SelectedRow') window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, handleTerminalWindow) core.suiService.openSUIWindow(window) if selected == 2: suiOptions = HashMap() if hiring >= 20: suiOptions.put(Long(1), '@player_structure:droid_bartender') if hiring >= 50: suiOptions.put(Long(2), '@player_structure:droid_power') if hiring >= 60: suiOptions.put(Long(3), '@player_structure:droid_wed') if hiring >= 90: suiOptions.put(Long(4), '@player_structure:droid_surgical') if hiring >= 100: suiOptions.put(Long(5), '@player_structure:droid_protocol') window = core.suiService.createListBox( ListBoxType.LIST_BOX_OK_CANCEL, '@player_structure:droid_type_t', '@player_structure:droid_type_d', suiOptions, actor, None, 5) returnList = Vector() returnList.add('List.lstList:SelectedRow') window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, handleDroidWindow) core.suiService.openSUIWindow(window) return
def update(self, ss, when): strLine = Long.toString(when.getTimeInMillis()).encode('utf-8') strLine = strLine + ',' \ + Double.toString(market.getLastPrice(0,'XAG-OPEN'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'XAG-HIGH'))\ .encode('utf-8') + ',' \ + Double.toString(market.getLastPrice(0,'XAG-LOW'))\ .encode('utf-8') + ','\ + Double.toString(market.getLastPrice(0,'XAG-CLOSE'))\ .encode('utf-8') + ','\ + Long.toString(market.getLastVolume(0,'XAG'))\ .encode('utf-8') print strLine
def _get_from_dict_as_long(self, name, default_value=None): _method_name = '_get_from_dict_as_long' result = self._get_from_dict(name, default_value) try: result = Long(result).longValue() except NumberFormatException, nfe: _logger.warning('WLSDPLY-01571', result, name, self._program_name, default_value, nfe.getLocalizedMessage(), class_name=_class_name, method_name=_method_name) result = Long(default_value).longValue()
def get_images(gateway, datasets, orphaned=True): """Return all image ids and image names for provided dataset ids""" browse = gateway.getFacility(BrowseFacility) experimenter = gateway.getLoggedInUser() ctx = SecurityContext(experimenter.getGroupId()) images = [] for dataset_id in datasets: ids = ArrayList(1) ids.add(Long(dataset_id)) j = browse.getImagesForDatasets(ctx, ids).iterator() while j.hasNext(): image = j.next() images.append({ 'Image Id': String.valueOf(image.getId()), 'Image Name': image.getName(), 'Dataset Id': dataset_id, 'Dataset Name': datasets[dataset_id], }) if orphaned: orphans = browse.getOrphanedImages( ctx, ctx.getExperimenter()) # need to pass user id (long) for image in orphans: images.append({ 'Image Id': String.valueOf(image.getId()), 'Image Name': image.getName(), 'Dataset Id': -1, 'Dataset Name': '<Orphaned>', }) return images
def download_image(gateway, image_id, path): "Download the files composing the image" transfer = gateway.getFacility(TransferFacility) user = gateway.getLoggedInUser() ctx = SecurityContext(user.getGroupId()) return transfer.downloadImage(ctx, path, Long(image_id))
def bioLinkPrompt(core, owner, target, option): if not 'shared_character_inventory' in target.getContainer().getTemplate(): owner.sendSystemMessage( '@base_player:must_biolink_to_use_from_inventory', 1) return bl = target.getStringAttribute('bio_link') #if not '<pending>' in bl: # owner.sendSystemMessage('@base_player:not_linked_to_holder', 1) # This should never occur, because a bio-linked item should have another radial # return owner.setAttachment('BioLinkItemCandidate', Long(target.getObjectID())) window = core.suiService.createSUIWindow('Script.messageBox', owner, owner, 0) window.setProperty('bg.caption.lblTitle:Text', '@sui:bio_link_item_title') window.setProperty('Prompt.lblPrompt:Text', '@sui:bio_link_item_prompt') window.setProperty('btnCancel:visible', 'True') window.setProperty('btnOk:visible', 'True') window.setProperty('btnUpdate:visible', 'False') window.setProperty('btnCancel:Text', '@cancel') window.setProperty('btnOk:Text', '@ui_radial:bio_link') returnList = Vector() window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, bioLinkProcess) window.addHandler(1, '', Trigger.TRIGGER_CANCEL, returnList, bioLinkCancel) core.suiService.openSUIWindow(window) return
def execute(self, mapping, form, request, response): # Extract the Hibernate Session Object servlet = self.getServlet() context = servlet.getServletContext() httpSession = request.getSession() curId = request.getParameter("id") print "Link ID=", curId # Removed due to Websphere/Hibernate classloader/classcast issues objFactory = context.getAttribute(HibernateUtilPlugin.KEY_NAME) # We have the needed object, we just need to invoke the factory method # curSess = SimpleAction.invokeVoidContextObject(objFactory, "org.hibernate.SessionFactory", "openSession") curSess = objFactory.openSession() tx = curSess.beginTransaction() # Extract the single entity (long line for query) queryRes = curSess.createQuery( "select l from org.spirit.bean.impl.BotListUserLink as l where l.id = :linkid" ) queryRes.setLong("linkid", Long(curId).longValue()) resLink = queryRes.uniqueResult() httpSession.setAttribute(BotListConsts.BOT_SINGLE_LINK, resLink) tx.commit() linksMsg = "Links Found 1" # Set the confirmation message messages = ActionMessages() msg = ActionMessage("userLink.info.list", linksMsg) messages.add("messagesconfirm", msg) self.saveMessages(request, messages) return mapping.findForward("success")
def bigendian2long(b): """Converts a series of 4 bytes in big-endian format to a Java Long. Arguments: b -- a string of 4 bytes that represent a word """ return Long(struct.unpack('>I', b)[0])
def __call__(self): grinder.logger.info( 'Checking grinder.agents to see if test needs to run') locationCount = len(helper.getLocationIds()) if locationCount > 0: grinder.logger.info( "Found %d locations for key %s" % (locationCount, helper.getLocationPropertyKey())) maxAgents = grinder.properties.getInt('grinder.agents', 100) if maxAgents <= grinder.agentNumber: grinder.logger.info( 'Not running agent %d because the max number of agents was %d' % (grinder.agentNumber, maxAgents)) return grinder.logger.info('Running agent') pullTest() pushTest() grinder.sleep( Long.parseLong(grinder.properties.get('time.between.sync.ms'))) else: grinder.logger.info('No location assigned to this agent: %s' % helper.getLocationPropertyKey())
class JUnitTest(Object): __proxymaker__ = MiniClampMaker __java_package__ = 'custom_proxymaker.tests' def testAddition(self): assertEquals(4, 1 + 3) testAddition._clamp = ClampMethod('testAddition', Void.TYPE, [], [], {Test: None}, [{}]) def testJavaException(self): raise JavaException() testJavaException._clamp = ClampMethod('testJavaException', Void.TYPE, [], [JavaException], {Test: { 'expected': JavaException }}, [{}]) def testTimeout(self): time.sleep(0.1) testTimeout._clamp = ClampMethod('testTimeout', Void.TYPE, [], [], {Test: { 'timeout': Long(1000) }}, [{}])
def __findGeoLocationsInDB(self, databasePath, abstractFile): if not databasePath: return try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException, SQLException) as ex: self._logger.log(Level.SEVERE, "Error opening database", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return try: resultSet = statement.executeQuery( "SELECT time, dest_lat, dest_lng, dest_title, dest_address, source_lat, source_lng FROM destination_history;") while resultSet.next(): time = Long.valueOf(resultSet.getString("time")) / 1000 dest_title = resultSet.getString("dest_title") dest_address = resultSet.getString("dest_address") dest_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lat")) dest_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lng")) source_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lat")) source_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lng")) artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_ROUTE) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_CATEGORY, general.MODULE_NAME, "Destination")) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, time)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_END, general.MODULE_NAME, dest_lat)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_END, general.MODULE_NAME, dest_lng)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_START, general.MODULE_NAME, source_lat)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_START, general.MODULE_NAME, source_lng)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME, general.MODULE_NAME, dest_title)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_LOCATION, general.MODULE_NAME, dest_address)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Google Maps History")) try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getServices().getBlackboard() blackboard.indexArtifact(artifact) except Blackboard.BlackboardException as ex: self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error("Failed to index GPS route artifact for keyword search.", artifact.getDisplayName()) except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing Google map locations to the blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: self._logger.log(Level.SEVERE, "Error closing the database", ex) self._logger.log(Level.SEVERE, traceback.format_exc())
def __findGeoLocationsInDB(self, databasePath, abstractFile): if not databasePath: return try: Class.forName("org.sqlite.JDBC") #load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException) as ex: self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return except (SQLException) as ex: # Error connecting to SQL databse. return resultSet = None try: resultSet = statement.executeQuery("SELECT timestamp, latitude, longitude, accuracy FROM CachedPosition;") while resultSet.next(): timestamp = Long.valueOf(resultSet.getString("timestamp")) / 1000 latitude = Double.valueOf(resultSet.getString("latitude")) longitude = Double.valueOf(resultSet.getString("longitude")) attributes = ArrayList() artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE, general.MODULE_NAME, latitude)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE, general.MODULE_NAME, longitude)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, timestamp)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Browser Location History")) # artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(),moduleName, accuracy)) # NOTE: originally commented out artifact.addAttributes(attributes); try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getServices().getBlackboard() blackboard.indexArtifact(artifact) except Blackboard.BlackboardException as ex: self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactTypeName()), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error("Failed to index GPS trackpoint artifact for keyword search.", artifact.getDisplayName()) except SQLException as ex: # Unable to execute browser location SQL query against database. pass except Exception as ex: self._logger.log(Level.SEVERE, "Error putting artifacts to blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: # Error closing database. pass
def _get_images_browser(gateway, dataset_id, group_id): browse = gateway.getFacility(BrowseFacility) user = gateway.getLoggedInUser() ctx = SecurityContext(group_id) ids = ArrayList(1) val = Long(dataset_id) ids.add(val) images = browse.getImagesForDatasets(ctx, ids) return images.iterator()
def __init__(self): head = 'Byte,Double,Float,Integer,Long,Short'.split(',') self.data = [[ Byte(Byte.MIN_VALUE), Double(Double.MIN_VALUE), Float(Float.MIN_VALUE), Integer(Integer.MIN_VALUE), Long(Long.MIN_VALUE), Short(Short.MIN_VALUE) ], [ Byte(Byte.MAX_VALUE), Double(Double.MAX_VALUE), Float(Float.MAX_VALUE), Integer(Integer.MAX_VALUE), Long(Long.MAX_VALUE), Short(Short.MAX_VALUE) ]] DefaultTableModel.__init__(self, self.data, head)
def __findTangoMessagesInDB(self, tangoDb, dataSource): if not tangoDb: return try: current_case = Case.getCurrentCaseThrows() # Create a helper to parse the DB tangoDbHelper = CommunicationArtifactsHelper(current_case.getSleuthkitCase(), self._PARSER_NAME, tangoDb.getDBFile(), Account.Type.TANGO ) resultSet = tangoDb.runQuery( "SELECT conv_id, create_time, direction, payload FROM messages ORDER BY create_time DESC;") while resultSet.next(): fromId = None toId = None conv_id = resultSet.getString("conv_id") # seems to wrap around the message found in payload after decoding from base-64 create_time = Long.valueOf(resultSet.getString("create_time")) / 1000 if resultSet.getString("direction") == "1": # 1 incoming, 2 outgoing direction = CommunicationDirection.INCOMING else: direction = CommunicationDirection.OUTGOING payload = resultSet.getString("payload") msgBody = TangoMessageAnalyzer.decodeMessage(conv_id, payload) messageArtifact = tangoDbHelper.addMessage( self._MESSAGE_TYPE, direction, fromId, toId, create_time, MessageReadStatus.UNKNOWN, "", # subject msgBody, "") except SQLException as ex: self._logger.log(Level.WARNING, "Error processing query result for Tango messages", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except TskCoreException as ex: self._logger.log(Level.SEVERE, "Failed to add Tango message artifacts.", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) except BlackboardException as ex: self._logger.log(Level.WARNING, "Failed to post artifacts.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) except NoCurrentCaseException as ex: self._logger.log(Level.WARNING, "No case currently open.", ex) self._logger.log(Level.WARNING, traceback.format_exc()) finally: tangoDb.close()
def convert_to_type(data_type, value, subtype=None, delimiter=None): """ Convert the value to the specified type. :param data_type: the type :param value: the value :param subtype: optional subtype for jarray type :param delimiter: optional delimiter to use for parsing :return: the value converted to the specified type """ _method_name = 'convert_to_type' # # TypeUtils.convertToType doesn't work for passwords... # if value is not None and data_type == 'password': # The password is an array of bytes coming back from the WLST get() method and only # java.lang.String() is able to properly convert it to the cipher text string. However, # we don't really want to return a java.lang.String to the caller so convert that Java # String back to a Python string...ugly but effective. new_value = str(String(value)) else: try: new_value = TypeUtils.convertToType(data_type, value, delimiter) except NumberFormatException, nfe: ex = exception_helper.create_alias_exception('WLSDPLY-08021', value, data_type, delimiter, nfe.getLocalizedMessage(), error=nfe) _logger.throwing(ex, class_name=_class_name, method_name=_method_name) raise ex if new_value is not None: try: if data_type == LONG: new_value = Long(new_value) elif data_type == JAVA_LANG_BOOLEAN: new_value = Boolean(new_value) elif data_type == JARRAY: if subtype is None or subtype == 'java.lang.String': new_value = _create_string_jarray(new_value) else: new_value = _create_mbean_array(new_value, subtype) elif data_type == LIST: new_value = list(new_value) elif data_type in ALIAS_DELIMITED_TYPES: # # This code intentionally ignores the delimiter value passed in and computes it from the data type. # This is required to handle the special case where the value we read from WLST might have a # different delimiter than the model value. In this use case, the value passed into the method # is the WLST value delimiter and the data_type is the preferred_model_type, so we compute the # model delimiter from the data_type directly. # delimiter = compute_delimiter_from_data_type(data_type, new_value) new_value = delimiter.join(new_value) except TypeError, te: ex = exception_helper.create_alias_exception('WLSDPLY-08021', value, data_type, delimiter, te) _logger.throwing(ex, class_name=_class_name, method_name=_method_name) raise ex
def getLicenseInfo(self, iemswdMboSet): iemswdMbo = iemswdMboSet.moveFirst() licenseNumList = ArrayList() orgList = ArrayList() tloamsoftwareList = ArrayList() while (iemswdMbo != None): licenseNumList.add(iemswdMbo.getString("LICENSENUM")) orgList.add(iemswdMbo.getString("ORGID")) tloamsoftwareList.add(Long(iemswdMbo.getLong("TLOAMSOFTWAREID"))) iemswdMbo = iemswdMboSet.moveNext() return licenseNumList, orgList, tloamsoftwareList
def handleUnregister(core, owner): city = core.playerCityService.getCityObjectIsIn(owner) if not city or not city.isCitizen(owner.getObjectID()): return if city.isElectionLocked(): owner.sendSystemMessage('@city/city:registration_locked', 0) return if city.isCandidate(owner.getObjectID()): city.getElectionList().remove(Long(owner.getObjectID())) owner.sendSystemMessage('@city/city:unregistered_race', 0) city.sendCandidateUnregisteredMail(owner) return
def handleTreasuryReport(core, owner, target, option): playerCity = core.playerCityService.getPlayerCity(owner) if not playerCity: return menuItems = TreeMap() menuItems.put(Long(1), '@city/city:treasury ' + str(playerCity.getCityTreasury())) window = core.suiService.createListBox(1, '@city/city:treasury_balance_t', '@city/city:treasury_balance_d', menuItems, owner, None, 0) core.suiService.openSUIWindow(window) return
def __findTangoMessagesInDB(self, databasePath, abstractFile): if not databasePath: return try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException, SQLException) as ex: self._logger.log(Level.SEVERE, "Error opening database", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return try: resultSet = statement.executeQuery( "SELECT conv_id, create_time, direction, payload FROM messages ORDER BY create_time DESC;") while resultSet.next(): conv_id = resultSet.getString("conv_id") # seems to wrap around the message found in payload after decoding from base-64 create_time = Long.valueOf(resultSet.getString("create_time")) / 1000 if resultSet.getString("direction") == "1": # 1 incoming, 2 outgoing direction = "Incoming" else: direction = "Outgoing" payload = resultSet.getString("payload") artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE) #create a call log and then add attributes from result set. artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, create_time)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION, general.MODULE_NAME, direction)) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT, general.MODULE_NAME, TangoMessageAnalyzer.decodeMessage(conv_id, payload))) artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE, general.MODULE_NAME, "Tango Message")) try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getServices().getBlackboard() blackboard.indexArtifact(artifact) except Blackboard.BlackboardException as ex: self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error("Failed to index Tango message artifact for keyword search.", artifact.getDisplayName()) except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing Tango messages to the blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: self._logger.log(Level.SEVERE, "Error closing database", ex) self._logger.log(Level.SEVERE, traceback.format_exc())
def getImageIds(gateway, datasetId): browse = gateway.getFacility(BrowseFacility) user = gateway.getLoggedInUser() ctx = SecurityContext(user.getGroupId()) ids = ArrayList(1) val = Long(datasetId) ids.add(val) images = browse.getImagesForDatasets(ctx, ids) j = images.iterator() imageIds = [] while j.hasNext(): image = j.next() imageIds.append(String.valueOf(image.getId()))
def handleManageMilitia(core, owner, target, option): playerCity = core.playerCityService.getPlayerCity(owner) if not playerCity: return menuItems = TreeMap() menuItems.put(Long(0), '@city/city:militia_new_t') for militiaId in playerCity.getMilitiaList(): militia = core.objectService.getObject(militiaId) if not militia: militia = core.objectService.getCreatureFromDB(militiaId) if militia: menuItems.put(Long(militiaId), militia.getCustomName()) returnList = Vector() returnList.add('List.lstList:SelectedRow') window = core.suiService.createListBox(1, '@city/city:militia_t', '@city/city:militia_d', menuItems, owner, None, 0) window.addHandler(0, '', Trigger.TRIGGER_OK, returnList, handleMilitiaListBox) core.suiService.openSUIWindow(window) return
def __activate__(self, context): self.velocityContext = context self.services = context["Services"] self.log = context["log"] self.sessionState = context["sessionState"] self.portalDir = context["portalDir"] self.__result = None self.__token = None self.__portalName = context["page"].getPortal().getName() self.__authors = [] self.__relatedResources = [] self.__enabledInAllViews = False self.__enabledInViews = [] self.__metadataPrefix = "" self.__sessionExpiry = Long.parseLong(JsonConfig().get("portal/oai-pmh/sessionExpiry")) self.__resumptionTokenList = self.sessionState.get("resumptionTokenList") if self.__resumptionTokenList == None: self.__resumptionTokenList = {} #Check if there's resumption token exist in the formData self.__currentToken = None resumptionToken = self.vc("formData").get("resumptionToken") if resumptionToken: if self.__resumptionTokenList.has_key(resumptionToken): self.__currentToken = self.__resumptionTokenList[resumptionToken] print " * oai.py: formData=%s" % self.vc("formData") self.vc("request").setAttribute("Content-Type", "text/xml") self.__request = OaiPmhVerb(self.vc("formData"), self.__currentToken, self.sessionState) if self.getError() is None and \ self.getVerb() in ["GetRecord", "ListIdentifiers", "ListRecords"]: ## Only list those data if the metadata format is enabled self.__metadataPrefix = self.vc("formData").get("metadataPrefix") if self.__metadataPrefix is None: self.__metadataPrefix = self.__currentToken.getMetadataPrefix() self.__enabledInAllViews = Boolean.parseBoolean(JsonConfig().get("portal/oai-pmh/metadataFormats/%s/enabledInAllViews" % self.__metadataPrefix, "false")) if self.__enabledInAllViews: self.__search() else: self.__enabledInViews = JsonConfig().getList("portal/oai-pmh/metadataFormats/%s/enabledViews" % self.__metadataPrefix) if self.__portalName in self.__enabledInViews: self.__search()
def map_to_vertx(value): """Converts a Jython type to a Vert.x type.""" if value is None: return value if isinstance(value, (list, tuple)): return org.vertx.java.core.json.JsonArray(map_seq_to_java(value)) elif isinstance(value, dict): return org.vertx.java.core.json.JsonObject(map_dict_to_java(value)) elif isinstance(value, Buffer): return value._to_java_buffer() elif isinstance(value, long): return Long(value) elif isinstance(value, float): return Double(value) elif isinstance(value, int): return Integer(value) return map_to_java(value)
def get_image_ids(gateway, dataset_id): """Return all image ids for given dataset""" browse = gateway.getFacility(BrowseFacility) experimenter = gateway.getLoggedInUser() ctx = SecurityContext(experimenter.getGroupId()) images = [] ids = ArrayList(1) ids.add(Long(dataset_id)) j = browse.getImagesForDatasets(ctx, ids).iterator() while j.hasNext(): image = j.next() images.append({ 'Image Id': String.valueOf(image.getId()), 'Image Name': image.getName(), 'Dataset Id': dataset_id, }) return images
def __call__(self): grinder.logger.info('Checking grinder.agents to see if test needs to run') locationCount = len(helper.getLocationIds()) if locationCount > 0: grinder.logger.info("Found %d locations for key %s" % (locationCount, helper.getLocationPropertyKey())) maxAgents = grinder.properties.getInt('grinder.agents', 100) if maxAgents <= grinder.agentNumber: grinder.logger.info('Not running agent %d because the max number of agents was %d' % (grinder.agentNumber, maxAgents)) return grinder.logger.info('Running agent') pullTest() pushTest() grinder.sleep(Long.parseLong(grinder.properties.get('time.between.sync.ms'))) else: grinder.logger.info('No location assigned to this agent: %s' % helper.getLocationPropertyKey())
def DiscoveryMain(Framework): SV_TYPE_SERVER = 0x00000002L SV_TYPE_DOMAIN_CTRL = 0x00000008L SV_TYPE_DOMAIN_BAKCTRL = 0x00000010L SV_TYPE_DOMAIN_ENUM = 0x80000000L OSHVResult = ObjectStateHolderVector() probe_name = Framework.getDestinationAttribute('probe_name') try: netUtil = MsNetworkUtil() domainsOutput = netUtil.doNetServerEnum('NULL', SV_TYPE_DOMAIN_ENUM, 'NULL') if domainsOutput != None: MsDomainsList = getMsDomainNameList (Framework) netUtilGetServer = MsNetworkUtil() for domainInfo in domainsOutput: domainName = domainInfo[0] domainType = Long.parseLong(domainInfo[1]) #Check if the current domain is to be discovered (if not, just continue to the next domain) if (MsDomainsList != None) and (domainName not in MsDomainsList): continue oshMsDomain = ObjectStateHolder('msdomain') oshMsDomain.setStringAttribute('data_name', domainName) if (domainType & SV_TYPE_DOMAIN_CTRL) !=0: oshMsDomain.setStringAttribute('msdomain_type', 'PDC') elif (domainType & SV_TYPE_DOMAIN_BAKCTRL) != 0: oshMsDomain.setStringAttribute('msdomain_type', 'BDC') hostsOutput = netUtilGetServer.doNetServerEnum('NULL', SV_TYPE_SERVER, domainName) if hostsOutput != None: oshMsDomain.setStringAttribute('probe_name', probe_name) OSHVResult.add(oshMsDomain) except: errorMsg = str(sys.exc_info()[1]).strip() Framework.reportError('Failed to discovery MS Domains :' + errorMsg) logger.errorException('Failed to discovery MS Domains') return OSHVResult
def __init__(self, additionalVariables): " initialize oracle database" self.__hostname = "localhost"; try: self.__hostname = InetAddress.getLocalHost().getCanonicalHostName() except: type, value, traceback = sys.exc_info() logger.severe("Hostname error:" + `value`) additionalVariables.add(RuntimeContextVariable("ORACLE_HOSTNAME", self.__hostname, RuntimeContextVariable.ENVIRONMENT_TYPE)) dbPassword = getVariableValue("DB_PASSWORD_ALL") if dbPassword and dbPassword.strip(): self.__sysPassword = dbPassword additionalVariables.add(RuntimeContextVariable("SYS_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE)) additionalVariables.add(RuntimeContextVariable("DBSNMP_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE)); additionalVariables.add(RuntimeContextVariable("SYSMAN_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE)) additionalVariables.add(RuntimeContextVariable("SYSTEM_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE)); else: self.__sysPassword = getVariableValue("SYS_PWD") dbDataLocation = getVariableValue("DB_DATA_LOC") if dbDataLocation and os.path.isdir(dbDataLocation): dbName = getVariableValue("DB_NAME") dbDataDir = os.path.join(dbDataLocation, dbName) if os.path.isdir(dbDataDir): logger.info("DB Data directory already exists:" + dbDataDir + "; Setting DB_INSTALL_OPTION to INSTALL_DB_SWONLY") additionalVariables.add(RuntimeContextVariable( "DB_INSTALL_OPTION", "INSTALL_DB_SWONLY", RuntimeContextVariable.ENVIRONMENT_TYPE)) tcpPort = getVariableValue("TCP_PORT"); self.__serviceName = getVariableValue("DB_GLOBAL_NAME") sb = StringBuilder("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)") sb.append("(HOST=").append(self.__hostname).append(")") sb.append("(PORT=").append(tcpPort).append("))") sb.append("(CONNECT_DATA=(SERVICE_NAME=").append(self.__serviceName).append(")))") self.__oracleServiceUrl = sb.toString() logger.info("Oracle listener service URL:" + self.__oracleServiceUrl) self.__jdbcUrl = "jdbc:oracle:thin:@" + self.__hostname +":"+ tcpPort + ":" + self.__serviceName runtimeContext.addVariable(RuntimeContextVariable("JDBC_URL", self.__jdbcUrl, RuntimeContextVariable.STRING_TYPE, "Oracle Thin Driver JDBC Url", True, RuntimeContextVariable.NO_INCREMENT)) oracleDriver = "oracle.jdbc.OracleDriver" runtimeContext.addVariable(RuntimeContextVariable("JDBC_DRIVER", oracleDriver, RuntimeContextVariable.STRING_TYPE, "Oracle Thin Driver class", True, RuntimeContextVariable.NO_INCREMENT)) self.__dbControl = Boolean.parseBoolean(getVariableValue("CONFIG_DBCONTROL", "false")) if self.__dbControl: self.__dbCtrlPort = getVariableValue("DBCONTROL_HTTP_PORT") additionalVariables.add(RuntimeContextVariable( "HTTPS_PORT", self.__dbCtrlPort, RuntimeContextVariable.STRING_TYPE)) oracleDir = getVariableValue("ORACLE_DIR") self.__markerFilePath = os.path.join(oracleDir, ".#dsoracle") self.__maintFilePath = getVariableValue("ORACLE_MAINT_FILE") dbInstallOption = getVariableValue("DB_INSTALL_OPTION") if dbInstallOption == "INSTALL_DB_AND_CONFIG": globalLockString = "OracleEnabler-" + self.__hostname logger.info("Requesting Global Lock with name: " + globalLockString) domain = proxy.getContainer().getCurrentDomain() options = domain.getOptions() maxActivationTimeOut = options.getProperty(Options.MAX_ACTIVATION_TIME_IN_SECONDS) lockTimeOut = Long.parseLong(maxActivationTimeOut) * 1000 acquired = ContainerUtils.acquireGlobalLock(globalLockString, lockTimeOut , lockTimeOut) if acquired: logger.info("Acquired Global lock with name: " + globalLockString) else: logger.severe("Could not acquire Global lock with name: " + globalLockString) raise Exception("Could not acquire Global lock with name: " + globalLockString)
def __findGeoLocationsInDB(self, databasePath, abstractFile): if not databasePath: return try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException) as ex: self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return except (SQLException) as ex: # Error opening database. return resultSet = None try: resultSet = statement.executeQuery( "SELECT time, dest_lat, dest_lng, dest_title, dest_address, source_lat, source_lng FROM destination_history;") while resultSet.next(): time = Long.valueOf(resultSet.getString("time")) / 1000 dest_title = resultSet.getString("dest_title") dest_address = resultSet.getString("dest_address") dest_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lat")) dest_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("dest_lng")) source_lat = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lat")) source_lng = GoogleMapLocationAnalyzer.convertGeo(resultSet.getString("source_lng")) attributes = ArrayList() artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_ROUTE) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_CATEGORY, general.MODULE_NAME, "Destination")) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, time)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_END, general.MODULE_NAME, dest_lat)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_END, general.MODULE_NAME, dest_lng)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE_START, general.MODULE_NAME, source_lat)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE_START, general.MODULE_NAME, source_lng)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_NAME, general.MODULE_NAME, dest_title)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_LOCATION, general.MODULE_NAME, dest_address)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, general.MODULE_NAME, "Google Maps History")) artifact.addAttributes(attributes) try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getServices().getBlackboard() blackboard.indexArtifact(artifact) except Blackboard.BlackboardException as ex: self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactID()), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error("Failed to index GPS route artifact for keyword search.", artifact.getDisplayName()) except SQLException as ex: # Unable to execute Google map locations SQL query against database. pass except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing Google map locations to the blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: # Error closing the database. pass
#print "parameters: ",parameters #end parameterScan #=============================================== # Get file path #=============================================== print "begin" message = container.getInputMessage(0) messageBody = message.getBodyContentAsString() #if inputPortNr == 0: print "input 0: ",messageBody file_path = messageBody message = container.getInputMessage(1) messageBody = Long.parseLong(message.getBodyContentAsString()) #if inputPortNr == 1: print "input 1: ",messageBody n_steps = messageBody message = container.getInputMessage(2) messageBody = Double.parseDouble(message.getBodyContentAsString()) print "input 2: ",messageBody integration_time = messageBody message = container.getInputMessage(3) messageBody = message.getBodyContentAsString() print "input 3: ",messageBody stringTable = messageBody.split(",") start_position_actuators_1D = []
def hamming64(l1, l2): return Long.bitCount(l1^l2)
def __generateUniqueId(self): random = Random().nextLong() systime = System.currentTimeMillis() return Long.toHexString(random ^ systime)
def __activate__(self, context): self.velocityContext = context self.log = self.vc("log") self.systemConfig = self.vc("systemConfig") self.session = self.vc("sessionState") self.response = self.vc("response") self.request = self.vc("request") self.msg = "" self.appId = None uri = URLDecoder.decode(self.request.getAttribute("RequestURI")) matches = re.match("^(.*?)/(.*?)/(.*?)/(.*?)/(.*?)$", uri) if matches and matches.group(5): self.appId = matches.group(5) if not self.appId: self.msg = "No appId specified" self.log.error(self.msg) return self.log.debug("Getting configuration for: " + self.appId) self.consumerName = self.systemConfig.getString(None, "authserver", self.appId, "name") self.sharedKey = self.systemConfig.getString(None, "authserver", self.appId, "sharedKey") self.aud = self.systemConfig.getString(None, "authserver", self.appId, "aud") self.iss = self.systemConfig.getString(None, "authserver", self.appId, "iss") self.expiry = self.systemConfig.getInteger(None, "authserver", self.appId, "expiry") self.logoutUrl = self.systemConfig.getString(None, "authserver", self.appId, "logoutUrl") logout = self.request.getParameter("logout") if logout == "1": self.session.invalidate() self.response.sendRedirect(self.logoutUrl) return if not self.consumerName: self.msg = "Invalid configuration, no app name" self.log.error(self.msg) return if not self.sharedKey: self.msg = "Invalid shared Key" self.log.error(self.msg) return if not self.aud: self.msg = "Invalid aud" self.log.error(self.msg) return if not self.iss: self.msg = "Invalid iss" self.log.error(self.msg) return if not self.expiry: self.msg = "Invalid expiry" self.log.error(self.msg) return # Because we don't trust the configuration current_user = self.vc("page").authentication.get_username() isAdmin = self.vc("page").authentication.is_admin() # Admin only... if not isAdmin: self.msg = "Sorry, this page is only for administrators." self.log.error(self.msg) return # Get the roles... typ = "[\"" + "\",\"".join(self.vc("page").authentication.get_roles_list()) + "\"]" # Generating signature... dtNow = Date().getTime() now = dtNow / 1000 iat = now nbf = now - 1 exp = now + self.expiry secRandom = SecureRandom() jti = Long.toString(dtNow) + "_" + Integer.toString(secRandom.nextInt()) payload = Payload('{"iss":"%s", "sub":"%s", "aud":"%s", "iat":"%s", "nbf":"%s", "exp":"%s", "jti":"%s", "typ":%s}' % (self.iss, current_user, self.aud, iat, nbf, exp, jti, typ)) jwsHeader = JWSHeader(JWSAlgorithm.HS256) macSigner = MACSigner(self.sharedKey) jwsObject = JWSObject(jwsHeader, payload) jwsObject.sign(macSigner) self.jws = jwsObject.serialize()
print "Before optimization (%s) ... " % addTime.addString() tc.optimize( optimizationOptions['error'], optimizationOptions['maxIterations'], optimizationOptions['maxPlateau'] ) print "After optimization (%s) ... " %addTime.addString() # print "Write transformed images to file (%s) ... " % addTime.addString() print "Saving files into directory %s (%s) ... " % (itsFolder, addTime.addString()) for layer, ts in tiles.iteritems(): for patch, tileList in ts.iteritems(): width = shape[0] height = shape[1] stepX = 1 stepY = 1 filePath = itsFolder + display.project.getLoader().createIdPath(Long.toString(patch.getId()), 'it', '.tif') File(filePath).getParentFile().mkdirs() resultStack = ImageStack( width, height, 2 ) parameter1p = FloatProcessor( width, height ) parameter2p = FloatProcessor( width, height ) resultStack.setProcessor( parameter1p, 1 ) resultStack.setProcessor( parameter2p, 2 ) resultImage = ImagePlus("", resultStack) for idx, t in sorted( tileList.iteritems(), key=lambda x : x[0] ): model = zeros( 2, 'd' ) t.getModel().toArray( model ) x, y = subscriptToIndex[idx - 1] parameter1p.setf(x, y, inverseMapTransforms[layer][patch].getNewLinearTerm(model[0])) parameter2p.setf(x, y, inverseMapTransforms[layer][patch].getNewConstantTerm(model[0], model[1]))
def __findTangoMessagesInDB(self, databasePath, abstractFile, dataSource): if not databasePath: return try: Class.forName("org.sqlite.JDBC") # load JDBC driver connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath) statement = connection.createStatement() except (ClassNotFoundException) as ex: self._logger.log(Level.SEVERE, "Error loading JDBC driver", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) return except (SQLException) as ex: # Error opening database. return # Create a 'Device' account using the data source device id datasourceObjId = dataSource.getDataSource().getId() ds = Case.getCurrentCase().getSleuthkitCase().getDataSource(datasourceObjId) deviceID = ds.getDeviceId() deviceAccountInstance = Case.getCurrentCase().getSleuthkitCase().getCommunicationsManager().createAccountFileInstance(Account.Type.DEVICE, deviceID, general.MODULE_NAME, abstractFile) resultSet = None try: resultSet = statement.executeQuery( "SELECT conv_id, create_time, direction, payload FROM messages ORDER BY create_time DESC;") while resultSet.next(): conv_id = resultSet.getString("conv_id") # seems to wrap around the message found in payload after decoding from base-64 create_time = Long.valueOf(resultSet.getString("create_time")) / 1000 if resultSet.getString("direction") == "1": # 1 incoming, 2 outgoing direction = "Incoming" else: direction = "Outgoing" payload = resultSet.getString("payload") attributes = ArrayList() artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_MESSAGE) #create a call log and then add attributes from result set. attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, general.MODULE_NAME, create_time)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DIRECTION, general.MODULE_NAME, direction)) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_TEXT, general.MODULE_NAME, TangoMessageAnalyzer.decodeMessage(conv_id, payload))) attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_MESSAGE_TYPE, general.MODULE_NAME, "Tango Message")) artifact.addAttributes(attributes) try: # index the artifact for keyword search blackboard = Case.getCurrentCase().getServices().getBlackboard() blackboard.indexArtifact(artifact) except Blackboard.BlackboardException as ex: self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + str(artifact.getArtifactID()), ex) self._logger.log(Level.SEVERE, traceback.format_exc()) MessageNotifyUtil.Notify.error("Failed to index Tango message artifact for keyword search.", artifact.getDisplayName()) except SQLException as ex: # Unable to execute Tango messages SQL query against database. pass except Exception as ex: self._logger.log(Level.SEVERE, "Error parsing Tango messages to the blackboard", ex) self._logger.log(Level.SEVERE, traceback.format_exc()) finally: try: if resultSet is not None: resultSet.close() statement.close() connection.close() except Exception as ex: # Error closing database. pass
def _getIndex(self, even, odd): mergePolicy = LogDocMergePolicy() mergePolicy.setMergeFactor(1000) directory = RAMDirectory() self.dirs.append(directory) writer = self.getWriter(directory=directory, analyzer=SimpleAnalyzer(Version.LUCENE_CURRENT), maxBufferedDocs=2, mergePolicy=mergePolicy) if self.dvStringSorted: # Index sorted stringDVType = FieldInfo.DocValuesType.SORTED elif self.notSorted: # Index non-sorted stringDVType = FieldInfo.DocValuesType.BINARY else: # sorted anyway stringDVType = FieldInfo.DocValuesType.SORTED ft1 = FieldType() ft1.setStored(True) ft2 = FieldType() ft2.setIndexed(True) for i in xrange(len(self.data)): if (i % 2 == 0 and even) or (i % 2 == 1 and odd): doc = Document() doc.add(Field("tracer", self.data[i][0], ft1)) doc.add(TextField("contents", self.data[i][1], Field.Store.NO)) if self.data[i][2] is not None: doc.add(StringField("int", self.data[i][2], Field.Store.NO)) if self.supportsDocValues: doc.add(NumericDocValuesField("int_dv", Long.parseLong(self.data[i][2]))) if self.data[i][3] is not None: doc.add(StringField("float", self.data[i][3], Field.Store.NO)) if self.supportsDocValues: doc.add(FloatDocValuesField("float_dv", Float.parseFloat(self.data[i][3]))) if self.data[i][4] is not None: doc.add(StringField("string", self.data[i][4], Field.Store.NO)) if self.supportsDocValues: if stringDVType == FieldInfo.DocValuesType.SORTED: doc.add(SortedDocValuesField("string_dv", BytesRef(self.data[i][4]))) elif stringDVType == FieldInfo.DocValuesType.BINARY: doc.add(BinaryDocValuesField("string_dv", BytesRef(self.data[i][4]))) else: raise ValueError("unknown type " + stringDVType) if self.data[i][5] is not None: doc.add(StringField("custom", self.data[i][5], Field.Store.NO)) if self.data[i][6] is not None: doc.add(StringField("i18n", self.data[i][6], Field.Store.NO)) if self.data[i][7] is not None: doc.add(StringField("long", self.data[i][7], Field.Store.NO)) if self.data[i][8] is not None: doc.add(StringField("double", self.data[i][8], Field.Store.NO)) if self.supportsDocValues: doc.add(NumericDocValuesField("double_dv", Double.doubleToRawLongBits(Double.parseDouble(self.data[i][8])))) if self.data[i][9] is not None: doc.add(StringField("short", self.data[i][9], Field.Store.NO)) if self.data[i][10] is not None: doc.add(StringField("byte", self.data[i][10], Field.Store.NO)) if self.data[i][11] is not None: doc.add(StringField("parser", self.data[i][11], Field.Store.NO)) for f in doc.getFields(): if f.fieldType().indexed() and not f.fieldType().omitNorms(): Field.cast_(f).setBoost(2.0) writer.addDocument(doc) reader = writer.getReader() writer.close() return self.getSearcher(reader=reader)