Esempio n. 1
0
    def decode(self, input, final=False):
        error_function = codecs.lookup_error(self.errors)
        input_array = array('b', self.buffer + str(input))
        input_buffer = ByteBuffer.wrap(input_array)
        builder = StringBuilder(
            int(self.decoder.averageCharsPerByte() * len(input)))
        self.output_buffer.rewind()

        while True:
            result = self.decoder.decode(input_buffer, self.output_buffer,
                                         final)
            pos = self.output_buffer.position()
            self.output_buffer.rewind()
            builder.append(self.output_buffer.subSequence(0, pos))
            if result.isUnderflow():
                if not final:
                    # Keep around any remaining input for next call to decode
                    self.buffer = input_array[input_buffer.position(
                    ):input_buffer.limit()].tostring()
                else:
                    _process_incomplete_decode(self.encoding, input,
                                               error_function, input_buffer,
                                               builder)
                break
            _process_decode_errors(self.encoding, input, result,
                                   error_function, input_buffer, builder)

        return builder.toString()
Esempio n. 2
0
def _format_json_value(value):
    """
    Format the value as a JSON snippet.
    :param value: the value
    :return: the JSON snippet
    """
    builder = StringBuilder()
    if isinstance(value, basestring):
        value = value.replace('\\', '\\\\')
        builder.append('"').append(_quote_embedded_quotes(value)).append('"')
    elif isinstance(value, (types.ListType, types.TupleType)):
        if not value:
            builder.append('[]')
        else:
            builder.append('[')
            nexttime = False
            for entry in value:
                if nexttime:
                    builder.append(',')
                else:
                    nexttime = True
                builder.append(_format_json_value(entry))
            builder.append(']')
    else:
        builder.append(value)
    return builder.toString()
Esempio n. 3
0
    def getPayloadContent(self, payload):
        if payload is None:
            return ""

        try:
            sb = StringBuilder()
            reader = BufferedReader(InputStreamReader(payload.open(), "UTF-8"))
            line = reader.readLine()
            p = re.compile('\s*<\?xml.*\?>\s*')
            firstLine = True
            while line is not None:
                if firstLine:
                    if p.match(line) is not None:
                        self.log.debug("Ignoring xml declaration")
                        line = reader.readLine()
                    else:
                        sb.append(line).append("\n")
                        line = reader.readLine()
                    firstLine = False
                else:
                    sb.append(line).append("\n")
                    line = reader.readLine()
            payload.close()

            if sb:
                return sb
            return ""

        except Exception, e:
            return ""
Esempio n. 4
0
    def format_json_value(self, value):
        """
        Format the value as a JSON snippet.
        :param value: the value
        :return: the JSON snippet
        """
        import java.lang.StringBuilder as StringBuilder
        builder = StringBuilder()
        debug("DEBUG: value %s TYPE %s", value, type(value))
        if type(value) == bool or (type(value) == str and
                                   (value == 'true' or value == 'false')):
            if value:
                v = "true"
            else:
                v = "false"
            builder.append(v)
        elif type(value) == str:
            builder.append('"').append(
                self.quote_embedded_quotes(value)).append('"')
        elif type(value) == list:
            builder.append("[ ")
            ind = 0
            for list_item in value:
                if ind > 0:
                    builder.append(", ")
                builder.append('"').append(list_item).append('"')
                ind = ind + 1

            builder.append(" ]")
        else:
            builder.append(value)
        return builder.toString()
Esempio n. 5
0
	def getDoc(self, url):
# 		print "call doc on %s" % url
# 		doc=None;
# 		try:
# 			newurl = URL( url );
# 			dbf = DocumentBuilderFactory.newInstance();
# 			dbf.setNamespaceAware(True)
# 			db = dbf.newDocumentBuilder();
# 			doc = db.parse( newurl.openStream() );
# 			print doc
# 		except Exception, e:
# 			print 'Failed to reach a server.'
# 			print 'Details', str(e);
# 			
# 		return doc;
# 		print "getDoc called with %s" % url
    
    # Java method above no longer works.
		doc=None;
		try:
			responseBuilder = StringBuilder();
			
			newurl = URL( url );
			conn = newurl.openConnection();
			rd = BufferedReader( InputStreamReader(conn.getInputStream()) );
			
			line = rd.readLine();
			while line != None:
				responseBuilder.append(line + '\n');
				line = rd.readLine();
			rd.close();
		except Exception, e:
			print 'Failed to reach a server.'
			print 'Details', str(e);
			return doc;
Esempio n. 6
0
 def schemaFor(self, alias):
     """
     Returns string containing the schema of the specified alias
     """
     self.register_script()
     sb = StringBuilder()
     Schema.stringifySchema(sb, self.pig.dumpSchema(alias), DataType.TUPLE)
     return sb.toString()
Esempio n. 7
0
 def test_wrong_type(self):
     with self.assertRaises(ValueError):
         jarray.array([1, 2], 'x')
     with self.assertRaises(TypeError):
         jarray.array([1, 2])
     with self.assertRaises(TypeError):
         jarray.array([1, 2], 6)
     with self.assertRaises(TypeError):
         jarray.array([1, 2], StringBuilder())
Esempio n. 8
0
 def readInputStream(inputStream):
     reader = BufferedReader(InputStreamReader(inputStream))
     builder = StringBuilder()
     line = None
     while True:
         line = reader.readLine()
         if line is None:
             break
         builder.append(line)
         builder.append(System.getProperty("line.separator"))
     return builder.toString()
def generateTable(pathname, tableName, ft):
    builder = StringBuilder()
    builder.append("""# encoding: utf-8

import gvsig

from org.gvsig.fmap.dal import DALLocator

""")

    for attr in ft:
        builder.append("def add_attribute_%s(ft):\n" % attr.getName())
        descriptor(builder, attr)

    builder.append("def add_attributes_%s(ft):\n" % tableName)
    for attr in ft:
        builder.append("  add_attribute_%s(ft)\n" % attr.getName())

    builder.append("""

def configurar_featuretype_%s(ft):
""" % tableName)
    tags = ft.getTags()
    if tags != None and not tags.isEmpty():
        builder.append("  tags = ft.getTags()\n")
        for name in ft.getTags():
            value = tags.get(name)
            builder.append("  tags.set(").append(
                toSource(name)).append(", ").append(
                    toSource(value)).append(")\n")

    builder.append("""
  add_attributes_%s(ft)

def crearTabla_%s(connection):
  tableName = "%s"
  dataManager = DALLocator.getDataManager()
  server = dataManager.openServerExplorer(
      connection.getProviderName(),
      connection
  )
  params = server.getAddParameters(tableName)
  ft = params.getDefaultFeatureType()
  configurar_featuretype_%s(ft)

  server.add(tableName, params, False)

def main(*args):
    pass
""" % (tableName, tableName, tableName, tableName))
    f = open(pathname, "w")
    f.write(builder.toString())
    f.close()
Esempio n. 10
0
 def preprocess(text):
     """Tokenize and stop the input text."""
     ts = StandardTokenizer(Lucene.get_version(), StringReader(text.lower()))
     ts = StopFilter(Lucene.get_version(), ts,  StopAnalyzer.ENGLISH_STOP_WORDS_SET)
     string_builder = StringBuilder()
     ts.reset()
     char_term_attr = ts.addAttribute(CharTermAttribute.class_)
     while ts.incrementToken():
         if string_builder.length() > 0:
             string_builder.append(" ")
         string_builder.append(char_term_attr.toString())
     return string_builder.toString()
Esempio n. 11
0
        def read_all(reader):
            arrsize = 8 * 1024
            arr = zeros('c', arrsize)
            buffer = StringBuilder()
            numCharsRead = 0

            while numCharsRead != -1:
                numCharsRead = reader.read(arr, 0, arrsize)
                if numCharsRead != -1:
                    buffer.append(arr, 0, numCharsRead)

            return buffer.toString()
Esempio n. 12
0
def clickBtnDel(event):
    global sb
    l = sb.length()
    if (l == 0):
        return
    else:
        st = sb.substring(0, l - 1)
        tf.setText(st)  #show on text field
        sbNew = StringBuilder(
            st
        )  # now we have to convert the string into StringBuilder sowe pass the String into StringBuilder
        sb = sbNew  # again update in sb
Esempio n. 13
0
def stringify(stream):
    reader = BufferedReader(InputStreamReader(stream))
    out = StringBuilder()

    while True:
        line = reader.readLine()
        if line is None:
            break
        out.append(line)
        out.append("\n")

    reader.close()
    return out.toString()
Esempio n. 14
0
def _format_json_value(value):
    """
    Format the value as a JSON snippet.
    :param value: the value
    :return: the JSON snippet
    """
    import java.lang.StringBuilder as StringBuilder
    builder = StringBuilder()
    if type(value) == bool or (isinstance(value, types.StringTypes) and (value == 'true' or value == 'false')):
        builder.append(JBoolean.toString(value))
    elif isinstance(value, types.StringTypes):
        builder.append('"').append(_escape_text(value.strip())).append('"')
    else:
        builder.append(value)
    return builder.toString()
 def apply(self, client, args):
     target = DAO.getPlayers().getCharacter(args[0])
     if target is None:
         client.send(ConsoleMessage(0, "The target is missing"))
     else:
         sb = StringBuilder()
         for player in DAO.getPlayers().getByIp(target.getClient().getIP()):
             sb.append("Player ").append(player.getNickName())
             sb.append(" Level ").append(player.getLevel())
             sb.append(" PH ").append(player.getHonor())
             sb.append(" MapPos ").append(
                 player.getCurrentMap().posToString()).append("\n")
         sb.append("IP ").append(target.getClient().getIP())
         sb.append(" Nickname ").append(target.getAccount().nickName)
         client.send(ConsoleMessage(0, sb.toString()))
Esempio n. 16
0
def _format_json_value(value):
    """
    Format the value as a JSON snippet.
    :param value: the value
    :return: the JSON snippet
    """
    import java.lang.StringBuilder as StringBuilder
    builder = StringBuilder()
    if type(value) == bool or (type(value) == str and
                               (value == 'true' or value == 'false')):
        builder.append(JBoolean.toString(value))
    elif type(value) == str:
        builder.append('"').append(_quote_embedded_quotes(value)).append('"')
    else:
        builder.append(value)
    return builder.toString()
Esempio n. 17
0
    def buildPostDataFortoken(self, encodedJWT, softwareStatementId) :
		postParameters = LinkedHashMap()
		postParameters.put("scope", self.clientScopes)
		postParameters.put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
		postParameters.put("grant_type", "client_credentials")
		postParameters.put("client_id", softwareStatementId)
		postParameters.put("client_assertion", encodedJWT)

		postData = StringBuilder()
		for param in postParameters.entrySet():
			if postData.length() != 0:
				postData.append('&')
			postData.append(URLEncoder.encode(param.getKey(), "UTF-8"))
			postData.append('=')
			postData.append(URLEncoder.encode(String(param.getValue()), "UTF-8").replace("+", "%20"))
		print "Post data: "+postData.toString()
		return postData.toString()
Esempio n. 18
0
 def insert_sb(text, c1, c2):
     # Insert code points c1, c2 in the text, as a Java StringBuilder
     sb = StringBuilder()
     # c1 at the quarter point
     p1 = len(mat) // 4
     for c in mat.text[:p1]:
         sb.appendCodePoint(ord(c))
     sb.appendCodePoint(c1)
     # c2 at the three-quarter point
     p2 = 3 * p1
     for c in mat.text[p1:p2]:
         sb.appendCodePoint(ord(c))
     sb.appendCodePoint(c2)
     # Rest of text
     for c in mat.text[p2:]:
         sb.appendCodePoint(ord(c))
     return sb
    def generateNameUid(self, user):
        if self.userEnforceAttributesUniqueness == None:
            print "Asimba. Build local external uid. User enforce attributes uniqueness not specified"
            return None
        
        sb = StringBuilder()
        first = True
        for userAttributeName in self.userEnforceAttributesUniqueness:
            if not first:
                sb.append("!")
            first = False
            attribute_values_list = user.getAttributeValues(userAttributeName)
            if (attribute_values_list != None) and (attribute_values_list.size() > 0):
                first_attribute_value = attribute_values_list.get(0)
                sb.append(first_attribute_value)

        return sb.toString()
Esempio n. 20
0
	def getDoc(self, url):
		doc=None;
		try:
			responseBuilder = StringBuilder();
			
			newurl = URL( url );
			conn = newurl.openConnection();
			
			rd = BufferedReader( InputStreamReader(conn.getInputStream()) );
			
			line = rd.readLine();
			while line != None:
				responseBuilder.append(line + '\n');
				line = rd.readLine();
			rd.close();
		except Exception, e:
			print 'Failed to reach a server.'
			print 'Details', str(e);
			return doc;
Esempio n. 21
0
    def decode(self, input, errors='strict', final=True):
        error_function = codecs.lookup_error(errors)
        input_buffer = ByteBuffer.wrap(array('b', input))
        decoder = Charset.forName(self.encoding).newDecoder()
        output_buffer = CharBuffer.allocate(min(max(int(len(input) / 2), 256), 1024))
        builder = StringBuilder(int(decoder.averageCharsPerByte() * len(input)))

        while True:
            result = decoder.decode(input_buffer, output_buffer, False)
            pos = output_buffer.position()
            output_buffer.rewind()
            builder.append(output_buffer.subSequence(0, pos))
            if result.isUnderflow():
                if final:
                    _process_incomplete_decode(self.encoding, input, error_function, input_buffer, builder)
                break
            _process_decode_errors(self.encoding, input, result, error_function, input_buffer, builder)

        return builder.toString(), input_buffer.position()
Esempio n. 22
0
    def encode(self, input, final=False):
        error_function = codecs.lookup_error(self.errors)
        # workaround non-BMP issues - need to get the exact count of chars, not codepoints
        input_buffer = CharBuffer.allocate(StringBuilder(input).length())
        input_buffer.put(input)
        input_buffer.rewind()
        self.output_buffer.rewind()
        builder = StringIO()

        while True:
            result = self.encoder.encode(input_buffer, self.output_buffer, final)
            pos = self.output_buffer.position()
            self.output_buffer.rewind()
            builder.write(self.output_buffer.array()[0:pos].tostring())
            if result.isUnderflow():
                break
            _process_encode_errors(self.encoding, input, result, error_function, input_buffer, builder)

        return builder.getvalue()
Esempio n. 23
0
    def encode(self, input, errors='strict'):
        error_function = codecs.lookup_error(errors)
        # workaround non-BMP issues - need to get the exact count of chars, not codepoints
        input_buffer = CharBuffer.allocate(StringBuilder(input).length())
        input_buffer.put(input)
        input_buffer.rewind()
        encoder = Charset.forName(self.encoding).newEncoder()
        output_buffer = ByteBuffer.allocate(min(max(len(input) * 2, 256), 1024))
        builder = StringIO()

        while True:
            result = encoder.encode(input_buffer, output_buffer, True)
            pos = output_buffer.position()
            output_buffer.rewind()
            builder.write(output_buffer.array()[0:pos].tostring())
            if result.isUnderflow():
                break
            _process_encode_errors(self.encoding, input, result, error_function, input_buffer, builder)

        return builder.getvalue(), len(input)
Esempio n. 24
0
    def toString(self):
        i18nManager = ToolsLocator.getI18nManager()
        if self.exp != None:
            try:
                builder = StringBuilder()

                if self.exp != None:
                    builder.append(self.exp)
                    builder.append(", ")

                if self.name != None:
                    builder.append("Field: ")
                    builder.append(self.name)
                    builder.append(", ")

                if self.comboFilterResults != None:
                    builder.append("Filter: ")
                    if self.comboFilterResults == 0:
                        builder.append(
                            i18nManager.getTranslation("_use_selection"))
                    if self.comboFilterResults == 1:
                        builder.append(
                            i18nManager.getTranslation("_use_filter"))
                    else:
                        builder.append(i18nManager.getTranslation("_use_all"))
                    builder.append(", ")

                if self.filterResults != None:
                    builder.append(self.filterResults)
                if self.filterResults == None:
                    builder.append("None")

                return builder.toString()
            except java.lang.Throwable, ex:
                logger("Error creando bookmarks.", LOGGER_WARN, ex)
                raise ex
            except:
Esempio n. 25
0
    def __init__(self, encoding, namespace_separator):
        self.encoding = encoding
        self.CurrentLineNumber = 1
        self.CurrentColumnNumber = 0
        self._NextLineNumber = 1
        self._NextColumnNumber = 0
        self.ErrorLineNumber = -1
        self.ErrorColumnNumber = -1
        self.ErrorCode = None

        if namespace_separator is None:
            self.namespace_separator = namespace_separator
        elif isinstance(namespace_separator, basestring):
            self.namespace_separator = str(namespace_separator)
            if len(self.namespace_separator) > 1:
                error = ("namespace_separator must be at most one character, "
                         "omitted, or None")
                raise ValueError(error)
        else:
            error = ("ParserCreate() argument 2 must be string or None, "
                     "not %s" % type(namespace_separator).__name__)
            raise TypeError(error)

        # See http://bugs.jython.org/issue1537
        try:
            self._reader = XMLReaderFactory.createXMLReader(
                _mangled_xerces_parser_name)
        except:
            self._reader = XMLReaderFactory.createXMLReader(
                _xerces_parser_name)

        if self.namespace_separator is None:
            try:
                feature = "http://xml.org/sax/features/namespaces"
                self._reader.setFeature(feature, False)
            except SAXNotRecognizedException:
                error = ("namespace support cannot be disabled; "
                         "set namespace_separator to a string of length 1.")
                raise ValueError(error)

        self._base = None
        self._buffer_text = True
        self._returns_unicode = True

        self._data = StringBuilder()

        self._handler = XMLEventHandler(self)
        self._reader.setContentHandler(self._handler)
        self._reader.setErrorHandler(self._handler)
        self._reader.setDTDHandler(self._handler)
        self._reader.setEntityResolver(self._handler)

        sax_properties = ("lexical-handler", "declaration-handler")
        for name in sax_properties:
            try:
                name = "http://xml.org/sax/properties/" + name
                self._reader.setProperty(name, self._handler)
            except SAXNotRecognizedException:
                error = "can't set property %r" % name
                raise NotImplementedError(error)

        apache_features = (("nonvalidating/load-external-dtd", False), )
        for name, value in apache_features:
            try:
                name = "http://apache.org/xml/features/" + name
                self._reader.setFeature(name, value)
            except SAXNotRecognizedException:
                error = "can't set feature %r" % name
                raise NotImplementedError(error)

        # experimental
        #f = "http://xml.org/sax/features/external-general-entities"
        f = "http://xml.org/sax/features/external-parameter-entities"
        #self._reader.setFeature(f, False)

        # check
        f = "http://xml.org/sax/features/use-entity-resolver2"
        assert self._reader.getFeature(f)
Esempio n. 26
0
 class ObjectJArrayTest(AbstractJArrayTest, unittest.TestCase):
     type = StringBuilder
     default_value = None
     instance = StringBuilder("aaa")
    def execute(self, report, feature):
        if feature.getType().get("LID_ACCIDENTE") == None:
            # Si no es la tabla de accidentes no hacenos nada
            return
        titularidad_accidente = feature.get("TITULARIDAD_VIA")
        storeVehiculos = feature.getStore().getStoresRepository().getStore(
            "ARENA2_VEHICULOS")
        accidente = feature.get("ID_ACCIDENTE")

        if accidente != None:
            ## Rellenar por campos de la feature
            # Mantiene el none
            # no es lo mismo que llegue un None
            # a que se confirme porque no tiene valores en la tabla
            # de vehiculos con que es 0
            conteoPorFeature = {
                'NUM_TURISMOS': None,
                'NUM_FURGONETAS': None,
                'NUM_CAMIONES': None,
                'NUM_AUTOBUSES': None,
                'NUM_CICLOMOTORES': None,
                'NUM_MOTOCICLETAS': None,
                'NUM_BICICLETAS': None,
                'NUM_OTROS_VEHI': None
            }
            for key in conteoPorFeature.keys():
                value = feature.get(key)
                conteoPorFeature[key] = value

            ## Conteo por la tabla asociada de vehiculos
            builder = ExpressionUtils.createExpressionBuilder()
            expression = builder.eq(builder.variable("ID_ACCIDENTE"),
                                    builder.constant(accidente)).toString()
            #fset = storeVehiculos.getFeatureSet(expression)
            conteoPorTablas = {
                'NUM_TURISMOS': 0,
                'NUM_FURGONETAS': 0,
                'NUM_CAMIONES': 0,
                'NUM_AUTOBUSES': 0,
                'NUM_CICLOMOTORES': 0,
                'NUM_MOTOCICLETAS': 0,
                'NUM_BICICLETAS': 0,
                'NUM_OTROS_VEHI': 0
            }
            fset = storeVehiculos.getFeatureSet(expression).iterable()
            for f in fset:
                tipoVehiculo = f.get("TIPO_VEHICULO")
                keyValue = self.getKeyFromTypeVehicle(tipoVehiculo)
                if keyValue != None:
                    conteoPorTablas[keyValue] += 1
            DisposeUtils.dispose(fset)
            DisposeUtils.dispose(storeVehiculos)
            toReport = False
            builder = StringBuilder()
            for key in conteoPorTablas.keys():
                if conteoPorTablas[key] != conteoPorFeature[key]:
                    if toReport:
                        builder.append(", ")
                    toReport = True
                    builder.append(key + " valor:" +
                                   str(conteoPorFeature[key]) +
                                   " correccion:" + str(conteoPorTablas[key]))

            if toReport:
                report.add(
                    feature.get("ID_ACCIDENTE"),
                    CODERR_VEHICULOS_NO_COINCIDEN,
                    "Vehiculos no coinciden: %s." % (builder.toString(), ),
                    fixerId="UpdateCountVehicles",
                    selected=True,
                    NUM_TURISMOS=conteoPorTablas['NUM_TURISMOS'],
                    NUM_FURGONETAS=conteoPorTablas['NUM_FURGONETAS'],
                    NUM_CAMIONES=conteoPorTablas['NUM_CAMIONES'],
                    NUM_AUTOBUSES=conteoPorTablas['NUM_AUTOBUSES'],
                    NUM_CICLOMOTORES=conteoPorTablas['NUM_CICLOMOTORES'],
                    NUM_MOTOCICLETAS=conteoPorTablas['NUM_MOTOCICLETAS'],
                    NUM_BICICLETAS=conteoPorTablas['NUM_BICICLETAS'],
                    NUM_OTROS_VEHI=conteoPorTablas['NUM_OTROS_VEHI'])
Esempio n. 28
0
from java.lang import StringBuilder
from java.io import BufferedReader, InputStreamReader
from java.net import URL

from java.io import File
from org.w3c.dom import Document

from javax.xml.parsers import DocumentBuilderFactory
from javax.xml.parsers import DocumentBuilder
from javax.xml.transform.dom import DOMSource

from javax.xml.transform import Transformer, TransformerFactory
from javax.xml.transform.stream import StreamResult

responseBuilder = StringBuilder()
ru = 'http://172.23.106.80:8080/SlapWebServices/ReadOnlyService'

url = URL(ru)
'''
conn = url.openConnection();
rd = BufferedReader( InputStreamReader(conn.getInputStream()) );
line = rd.readLine();
while line != None:
	responseBuilder.append(line + '\n');
	line = rd.readLine();
rd.close();
txt=responseBuilder.toString();
'''

dbf = DocumentBuilderFactory.newInstance()
db = dbf.newDocumentBuilder()
Esempio n. 29
0
from Parameters import Parameters

readme_fpath = os.path.join(script_path, "README.txt")
params = Parameters()

title = "Membrane Blebbing version " + Parameters._version_string

try:
    f = open(readme_fpath, "rb")
    text = f.readlines()
except:
    raise IOError("Error reading README.txt")
finally:
    f.close()

sb = StringBuilder()
for line in text:
    sb.append(line)

panel = Panel()

txtArea = JTextArea(sb.toString())
txtArea.setEditable(False)
txtArea.setLineWrap(True)
txtArea.setWrapStyleWord(True)
scrollpane = JScrollPane(txtArea)
scrollpane.setPreferredSize(Dimension(500, 200))
panel.add(scrollpane)
dialog = NonBlockingGenericDialog(title)
#for line in text:
#	dialog.addMessage(line);
Esempio n. 30
0
def execSshRemoteUsrPwd(hostname,
                        username,
                        password,
                        commandsSemiColonSeperated,
                        sessionTimeoutSecs=0,
                        waitForOutput=True):
    _hostname = hostname
    _username = username
    _password = password
    _command = commandsSemiColonSeperated

    jsch = JSch()

    session = jsch.getSession(_username, _hostname, 22)
    session.setPassword(_password)
    config = Properties()
    config.put("StrictHostKeyChecking", "no")
    config.put("GSSAPIAuthentication", "no")
    config.put("UnknownHostVerification", "no")
    #config.put("PreferredAuthentications", "publickey");
    session.setConfig(config)

    if (sessionTimeoutSecs > 0): session.setTimeout(sessionTimeoutSecs * 10)

    print 'Logging into Remote SSH Shell u/p Auth...'

    try:
        if (sessionTimeoutSecs > 0):
            session.connect(sessionTimeoutSecs * 1000)
        else:
            session.connect()
    except:
        return 'None'

    channel = session.openChannel("exec")
    channel.setCommand('source ~/.bash_profile 2>/dev/null; ' + _command)

    outputBuffer = StringBuilder()

    stdin = channel.getInputStream()
    stdinExt = channel.getExtInputStream()

    channel.connect(sessionTimeoutSecs * 1000)

    if (waitForOutput == True):
        while (1):
            n = stdin.read()
            if n == -1:
                break
            if (chr(n) == '\n'):
                outputBuffer.append('|')
            elif (chr(n) == '\r'):
                outputBuffer.append('|')
            else:
                outputBuffer.append(chr(n))

        while (1):
            n = stdinExt.read()
            if n == -1:
                break
            if (chr(n) == '\n'):
                outputBuffer.append('|')
            elif (chr(n) == '\r'):
                outputBuffer.append('|')
            else:
                outputBuffer.append(chr(n))

    else:
        sleep(sessionTimeoutSecs)

    print "Command on: " + hostname + " : " + _command
    print "\toutput: " + outputBuffer.toString()

    channel.disconnect()
    session.disconnect()

    del channel
    del session

    return outputBuffer.toString()