Esempio n. 1
0
class SSLSocket(object):
    def __init__(self, java_socket, keyfile=None):
        self.java_ssl_socket = self._nycs_socket(java_socket, keyfile)
        self._in_buf = BufferedInputStream(self.java_ssl_socket.getInputStream())
        self._out_buf = BufferedOutputStream(self.java_ssl_socket.getOutputStream())

    # Not-Yet-Commons-SSL Socket
    def _nycs_socket(self, java_socket, keyfile=None):
        host = java_socket.getInetAddress().getHostAddress()
        port = java_socket.getPort()
        client = SSLClient()
        client.setCheckHostname(False)
        client.setCheckExpiry(False)
        client.setCheckCRL(False)
        client.setKeyMaterial(KeyMaterial(keyfile, ""))
        client.setTrustMaterial(TrustMaterial.TRUST_ALL)
        java_ssl_socket = client.createSocket(java_socket, host, port, 0)
        java_ssl_socket.startHandshake()
        return java_ssl_socket

    def recv(self, n=4096):
        data = jarray.zeros(n, 'b')
        m = self._in_buf.read(data, 0, n)
        if m <= 0:
            return ""
        if m < n:
            data = data[:m]
        return data.tostring()

    def send(self, s):
        self._out_buf.write(s)
        self._out_buf.flush()
        return len(s)
Esempio n. 2
0
class SSLSocket(object):
    def __init__(self, java_socket, keyfile=None):
        self.java_ssl_socket = self._nycs_socket(java_socket, keyfile)
        self._in_buf = BufferedInputStream(
            self.java_ssl_socket.getInputStream())
        self._out_buf = BufferedOutputStream(
            self.java_ssl_socket.getOutputStream())

    # Not-Yet-Commons-SSL Socket
    def _nycs_socket(self, java_socket, keyfile=None):
        host = java_socket.getInetAddress().getHostAddress()
        port = java_socket.getPort()
        client = SSLClient()
        client.setCheckHostname(False)
        client.setCheckExpiry(False)
        client.setCheckCRL(False)
        client.setKeyMaterial(KeyMaterial(keyfile, ""))
        client.setTrustMaterial(TrustMaterial.TRUST_ALL)
        java_ssl_socket = client.createSocket(java_socket, host, port, 0)
        java_ssl_socket.startHandshake()
        return java_ssl_socket

    def recv(self, n=4096):
        data = jarray.zeros(n, 'b')
        m = self._in_buf.read(data, 0, n)
        if m <= 0:
            return ""
        if m < n:
            data = data[:m]
        return data.tostring()

    def send(self, s):
        self._out_buf.write(s)
        self._out_buf.flush()
        return len(s)
 def saveSprite(self, spritefileName, spriteName, bitmap):
 
     # Create a subdirectory of the SpriteViewer directory for the current
     # set of sprites.
     subDir = File(Environment.DIRECTORY_DOWNLOADS, "SpriteViewer")
     
     outputFile = Files.createExternalFile(subDir.getPath(),
         spritefileName, spriteName, "", ".png")
     
     stream = BufferedOutputStream(FileOutputStream(outputFile))
     bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream)
     stream.flush()
     
     Toast.makeText(self, "Saved " + outputFile.getPath(), Toast.LENGTH_LONG).show()
 def viewSprite(self, bitmap):
 
     self.temp_file = Files.createExternalFile(Environment.DIRECTORY_DOWNLOADS,
         "SpriteViewer", ".temp", "", ".png")
     
     stream = BufferedOutputStream(FileOutputStream(self.temp_file))
     bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream)
     stream.flush()
     # Closing the file with close() will cause an exception.
     
     intent = Intent()
     intent.setAction(Intent.ACTION_VIEW)
     intent.setDataAndType(Uri.parse("file://" + self.temp_file.getPath()), "image/png")
     self.startActivity(intent)
Esempio n. 5
0
    def __init__(self, cmd, capturestderr=0, bufsize=-1):
        """The parameter 'cmd' is the shell command to execute in a
        sub-process.  Can be either a sequence of executable
        and arguments, or a shell command.
        The 'capturestderr' flag, if true, specifies that
        the object should capture standard error output of the child process.
        The default is false.  If the 'bufsize' parameter is specified, it
        specifies the size of the I/O buffers to/from the child process.
        """
        self.process = shellexecute(cmd)
        self._tochild = self.process.getOutputStream()
        self._fromchild = self.process.getInputStream()
        if capturestderr:
            self._childerr = self.process.getErrorStream()
        else:
            self._childerr = None
        import threading
        self.childWaiterLock = threading.Lock()

        if bufsize > 0:
            self._tochild = BufferedOutputStream(self._tochild, bufsize)
            self._fromchild = BufferedInputStream(self._fromchild, bufsize)
            if self._childerr:
                self._childerr = BufferedInputStream(self._childerr, bufsize)

        self.tochild = PyFile(self._tochild)
        self.fromchild = PyFile(self._fromchild)
        if self._childerr:
            self.childerr = PyFile(self._childerr)
Esempio n. 6
0
class SafeUNIXSocket(object):
    def __init__(self, socketpath):
        self.sock = AFUNIXSocket.newInstance()
        self.sock.connect(AFUNIXSocketAddress(File(socketpath)))
        self._in_buf = BufferedInputStream(self.sock.getInputStream())
        self._out_buf = BufferedOutputStream(self.sock.getOutputStream())

    def recv(self, n=4096):
        data = jarray.zeros(n, 'b')
        m = self._in_buf.read(data, 0, n)
        if m <= 0:
            return ""
        if m < n:
            data = data[:m]
        return data.tostring()

    def send(self, s):
        self._out_buf.write(s)
        self._out_buf.flush()
        return len(s)
Esempio n. 7
0
class SafeUNIXSocket(object):
    def __init__(self, socketpath):
        self.sock = AFUNIXSocket.newInstance()
        self.sock.connect(AFUNIXSocketAddress(File(socketpath)))
        self._in_buf = BufferedInputStream(self.sock.getInputStream())
        self._out_buf = BufferedOutputStream(self.sock.getOutputStream())

    def recv(self, n=4096):
        data = jarray.zeros(n, 'b')
        m = self._in_buf.read(data, 0, n)
        if m <= 0:
            return ""
        if m < n:
            data = data[:m]
        return data.tostring()

    def send(self, s):
        self._out_buf.write(s)
        self._out_buf.flush()
        return len(s)
Esempio n. 8
0
	def enhance( self, contentDescriptor, content, connector_url, cq_user, cq_password, asset_doWebDAV, asset_skeleton, asset_transformationRules, asset_drive, asset_filenameAttr, asset_pathAttr ):
		
		# Validate Parameters
		if not self.validInputs(connector_url,cq_user,cq_password,asset_drive,asset_filenameAttr,asset_pathAttr,"page_query","page_querylib","ia_path","ia_cacheCols"): return
		
		if asset_doWebDAV:
			# Save Asset to WebDAV Drive
			drive = asset_drive[0]
			path = re.sub("/content/dam/","/var/dam/",contentDescriptor.metadata[asset_pathAttr])
			filename = contentDescriptor.metadata[asset_filenameAttr]
			filepath = "%s:%s/%s" % (drive,path,filename)
			
			if not exists("%s:%s" % (drive,path)): makedirs("%s:%s" % (drive,path))
			file = BufferedOutputStream(FileOutputStream(filepath))
			data = Base64.decode(content.contentData)
			try: 
				file.write(data, 0, len(data))
				file.close()
				contentDescriptor.metadata["Load.Status"] = "SUCCESS"
			except:
				logger.error("! [WebDAV] Could not write %s to file system" % (contentDescriptor.url))
				file.close()
				contentDescriptor.metadata["Load.Status"] = "FAILURE"
				contentDescriptor.metadata["Load.Failure Reason"] = "! [WebDAV] Could not deposit file on file system"
				return
			
		# Build & Send Asset Metadata Payload if required
		if asset_skeleton and asset_transformationRules:
			
			# Build Payload
			payload = self.buildAssetPayload(asset_skeleton,asset_transformationRules,content,contentDescriptor)
			
			# HTTP Connection Details
			client = HttpClient()
			base64EncodedCredentials = Base64.encodeString("%s:%s" % (cq_user,cq_password))
			header = Header("Authorization", "Basic %s" % (base64EncodedCredentials))
			
			# Send Metadata Payload
			post = PostMethod(connector_url)
			post.addRequestHeader(header)
			get = GetMethod(connector_url)
			get.addRequestHeader(header)
			[loadStatus, failureReason] = self.sendPayload(client,get,post,payload,contentDescriptor.url)
			contentDescriptor.metadata["Load.Status"] = loadStatus
			if loadStatus == "SUCCESS":
				contentDescriptor.metadata["Load.Failure Reason"] = ''
			else:
				contentDescriptor.metadata["Load.Failure Reason"] = "Metadata: "+failureReason
				logger.error("! [METADATA] %s" % (failureReason))		
Esempio n. 9
0
 def save(self, parent, format):
     chooser = JFileChooser()
     # filter = FileNameExtensionFilter(
     #     format + " files",
     #     array([format, format.lower()], String))
     # chooser.setFileFilter(filter);
     returnVal = chooser.showSaveDialog(parent)
     if returnVal == JFileChooser.APPROVE_OPTION:
         fileName = chooser.getSelectedFile().getPath()
         if not fileName.upper().endswith('.' + format):
             fileName += '.' + format.lower()
         file = File(fileName)
     else:
         return
     if format == 'PNG':
         ChartUtils.saveChartAsPNG(file, self.chart, self.exportX,
                                   self.exportY)
     elif format == 'SVG':
         domImpl = GenericDOMImplementation.getDOMImplementation()
         doc = domImpl.createDocument(None, "svg", None)
         svgGen = SVGGraphics2D(doc)
         svgGen.getGeneratorContext().setPrecision(6)
         self.chart.draw(
             svgGen, Rectangle2D.Double(0, 0, self.exportX, self.exportY),
             None)
         out = OutputStreamWriter(FileOutputStream(file), "UTF-8")
         svgGen.stream(out, True)  #True is for useCSS
         out.close()
     elif format == 'PDF':
         mapper = DefaultFontMapper()
         pageSize = Rectangle(self.exportX, self.exportY)
         doc = TextDocument(pageSize, 50, 50, 50, 50)
         out = BufferedOutputStream(FileOutputStream(file))
         writer = PdfWriter.getInstance(doc, out)
         doc.open()
         cb = writer.getDirectContent()
         tp = cb.createTemplate(self.exportX, self.exportY)
         g2 = tp.createGraphics(self.exportX, self.exportY, mapper)
         r2D = Rectangle2D.Double(0, 0, self.exportX, self.exportY)
         self.chart.draw(g2, r2D)
         g2.dispose()
         cb.addTemplate(tp, 0, 0)
         doc.close()
    public void setExplosionPos(double x, double y) {
        rangeView.setExplosionPos(x,y);
    }

    public void setScale(int value) {
        rangeView.setScale(value);
    }

    public int getScale() {
        return rangeView.getScale();
    }

    public void connectToServer(String host, int port ) throws IOException {
        Socket socket = new Socket(host, port);
        in = new BufferedReader( new InputStreamReader( socket.getInputStream()));
        out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    }

    public void drawRangeView() {
        rangeView.repaint();
    }

    private static void  printHelpText() {
        System.out.println(
            "----------------------------------------------------------------------\n"
          + "usage: java jar LanderDisplay.jar <port-number>\n"
          + "----------------------------------------------------------------------\n"
          );
    }

    public enum ModelState { INACTIVE, READY, ACTIVE }
Esempio n. 11
0
 def __init__(self, java_socket, keyfile=None):
     self.java_ssl_socket = self._nycs_socket(java_socket, keyfile)
     self._in_buf = BufferedInputStream(
         self.java_ssl_socket.getInputStream())
     self._out_buf = BufferedOutputStream(
         self.java_ssl_socket.getOutputStream())
Esempio n. 12
0
 def __init__(self, socketpath):
     self.sock = AFUNIXSocket.newInstance()
     self.sock.connect(AFUNIXSocketAddress(File(socketpath)))
     self._in_buf = BufferedInputStream(self.sock.getInputStream())
     self._out_buf = BufferedOutputStream(self.sock.getOutputStream())
Esempio n. 13
0
    def enhance(self, contentDescriptor, content, connector_url, cq_user,
                cq_password, asset_doWebDAV, asset_skeleton,
                asset_transformationRules, asset_drive, asset_filenameAttr,
                asset_pathAttr):

        # Validate Parameters
        if not self.validInputs(connector_url, cq_user, cq_password,
                                asset_drive, asset_filenameAttr,
                                asset_pathAttr, "page_query", "page_querylib",
                                "ia_path", "ia_cacheCols"):
            return

        if asset_doWebDAV:
            # Save Asset to WebDAV Drive
            drive = asset_drive[0]
            path = re.sub("/content/dam/", "/var/dam/",
                          contentDescriptor.metadata[asset_pathAttr])
            filename = contentDescriptor.metadata[asset_filenameAttr]
            filepath = "%s:%s/%s" % (drive, path, filename)

            if not exists("%s:%s" % (drive, path)):
                makedirs("%s:%s" % (drive, path))
            file = BufferedOutputStream(FileOutputStream(filepath))
            data = Base64.decode(content.contentData)
            try:
                file.write(data, 0, len(data))
                file.close()
                contentDescriptor.metadata["Load.Status"] = "SUCCESS"
            except:
                logger.error("! [WebDAV] Could not write %s to file system" %
                             (contentDescriptor.url))
                file.close()
                contentDescriptor.metadata["Load.Status"] = "FAILURE"
                contentDescriptor.metadata[
                    "Load.Failure Reason"] = "! [WebDAV] Could not deposit file on file system"
                return

        # Build & Send Asset Metadata Payload if required
        if asset_skeleton and asset_transformationRules:

            # Build Payload
            payload = self.buildAssetPayload(asset_skeleton,
                                             asset_transformationRules,
                                             content, contentDescriptor)

            # HTTP Connection Details
            client = HttpClient()
            base64EncodedCredentials = Base64.encodeString(
                "%s:%s" % (cq_user, cq_password))
            header = Header("Authorization",
                            "Basic %s" % (base64EncodedCredentials))

            # Send Metadata Payload
            post = PostMethod(connector_url)
            post.addRequestHeader(header)
            get = GetMethod(connector_url)
            get.addRequestHeader(header)
            [loadStatus,
             failureReason] = self.sendPayload(client, get, post, payload,
                                               contentDescriptor.url)
            contentDescriptor.metadata["Load.Status"] = loadStatus
            if loadStatus == "SUCCESS":
                contentDescriptor.metadata["Load.Failure Reason"] = ''
            else:
                contentDescriptor.metadata[
                    "Load.Failure Reason"] = "Metadata: " + failureReason
                logger.error("! [METADATA] %s" % (failureReason))
Esempio n. 14
0
 def __init__(self, socketpath):
     self.sock = AFUNIXSocket.newInstance()
     self.sock.connect(AFUNIXSocketAddress(File(socketpath)))
     self._in_buf = BufferedInputStream(self.sock.getInputStream())
     self._out_buf = BufferedOutputStream(self.sock.getOutputStream())
Esempio n. 15
0
def dump_patterns(inputs,outputs,outfile,calibration_percentage=0.75,skip = 365,append=0,
		  fast_write=0):
    '''
    dump_patterns(inputs,outputs,outfile,calibration_percentage=0.75,append=0):
    dumps the patterns to the given outfile.
    outfile.cal which contains calibration% of the points
    outfile.ver which contains validation% = 100 - calibration% of the points
    append=1 appends to the previous .cal and .ver files if they exist
    '''
    bufsize=15000
    #fast_write=0
    prev_no_patterns = [0,0]
    if append:
	cfh = open(outfile+'.cal','r+',bufsize)
	vfh = open(outfile+'.ver','r+',bufsize)
	id = 0
	for fh in [cfh,vfh]:
	    while 1:
		line = string.strip(fh.readline())
		if string.find(line,'No. of patterns') >=0:
		    prev_no_patterns[id] = int(line[string.find(line,':')+1:])
		if string.find(line,'Input pattern')>=0: break
	    fh.seek(0)
	    id = id + 1
    else:
	if fast_write:
	    cfh = PrintStream(BufferedOutputStream(FileOutputStream(outfile+'.cal')))
	    vfh = PrintStream(BufferedOutputStream(FileOutputStream(outfile+'.ver')))
	else:
	    cfh = open(outfile+'.cal','w',bufsize)
	    vfh = open(outfile+'.ver','w',bufsize)
    #
    #if append:
    #	print 'Prev # of patterns = %s'%prev_no_patterns
    npatterns = len(inputs[0]) - skip # skip beginning
    #print 'Time Window of inputs[0] %s'%str(inputs[0].getTimeWindow())
    #print npatterns,len(inputs[0]),skip
    ncalibs = calibration_percentage*npatterns
    ninputs = len(inputs)
    noutputs = len(outputs)
    #print 'Ncalibs: %d & Nverse: %d'%(ncalibs,npatterns-ncalibs)
    if append or not fast_write:
	cfh.write('''SNNS pattern definition file V3.2
generated at date                : %s
No. of patterns                  : %d
No. of input units               : %d
No. of output units              : %d

'''%(time.ctime(time.time()),ncalibs+prev_no_patterns[0],ninputs,noutputs))
	vfh.write('''SNNS pattern definition file V3.2
generated at date                : %s
No. of patterns                  : %d
No. of input units               : %d
No. of output units              : %d

'''%(time.ctime(time.time()),npatterns-ncalibs+prev_no_patterns[1],ninputs,noutputs))
    else:
	cfh.print('''SNNS pattern definition file V3.2
generated at date                : %s
No. of patterns                  : %d
No. of input units               : %d
No. of output units              : %d

'''%(time.ctime(time.time()),ncalibs+prev_no_patterns[0],ninputs,noutputs))
	vfh.print('''SNNS pattern definition file V3.2
generated at date                : %s
No. of patterns                  : %d
No. of input units               : %d
No. of output units              : %d

'''%(time.ctime(time.time()),npatterns-ncalibs+prev_no_patterns[1],ninputs,noutputs))
    #
    #goto end of file
    if append:
	for fh in [cfh,vfh]:
	    if fast_write:
		fh.close()
	    else:
		fh.seek(0,2)
	if fast_write:
	    cfh = PrintStream(BufferedOutputStream(FileOutputStream(outfile+'.cal',1)))
	    vfh = PrintStream(BufferedOutputStream(FileOutputStream(outfile+'.ver',1)))
    #
    i=0
    all = inputs + outputs
    iterator = MultiIterator(all)
    npattern = 1
    nskip = 0
    nprint_intvl = npatterns/10
    nprints = 0
    while not iterator.atEnd():
	if npattern%nprint_intvl == 0:
	    nprints = nprints + 1
	    print 'Done: %d%%'%(nprints*10)
	if nskip < skip:
	    nskip=nskip+1
	    iterator.advance()
	    continue
	if npattern > npatterns: break
	el = iterator.getElement()
	j=0
	#print el
	if npattern <= ncalibs:
	    fh = cfh
	    pattern_no = npattern
	    prev_pattern_no = prev_no_patterns[0]
	else:
	    fh = vfh
	    pattern_no = npattern - ncalibs
	    prev_pattern_no = prev_no_patterns[1]
	if fast_write:
	    fh.println()
	    fh.println('# Input pattern %d:'%(pattern_no+prev_pattern_no))
	else:
	    fh.write('\n# Input pattern %d:\n'%(pattern_no+prev_pattern_no))
	while j < ninputs:
	    if fast_write:
		fh.print('%10.6f'%el.getY(j))
	    else:
		fh.write('%10.6f'%el.getY(j))
	    j=j+1
	if fast_write:
	    fh.println()
	    fh.println('# Output pattern %d:'%(pattern_no+prev_pattern_no))
	else:
	    fh.write('\n# Output pattern %d:\n'%(pattern_no+prev_pattern_no))
	while j < ninputs+noutputs:
	    if fast_write:
		fh.print('%10.6f'%el.getY(j))
	    else:
		fh.write('%10.6f'%el.getY(j))
	    j=j+1
	if fast_write:
	    fh.println()
	else:
	    fh.write('\n')
	npattern = npattern+1
	iterator.advance()
    #
    cfh.close()
    vfh.close()
from java.io import File as F
from java.io import FileInputStream as FI
from java.io import FileOutputStream as FO
from java.io import BufferedInputStream as BI
from java.io import BufferedOutputStream as BO
from java.util.zip import InflaterInputStream as II

file_read = F("file5.txt")
file_write = F("file6.txt")

bi = BI(II(FI(file_read)))
bo = BO(FO(file_write))

while True:
    val = bi.read()
    if val != -1:
        bo.write(val)
    else:
        break

bi.close()
bo.close()
Esempio n. 17
0
 def __init__(self, java_socket, keyfile=None):
     self.java_ssl_socket = self._nycs_socket(java_socket, keyfile)
     self._in_buf = BufferedInputStream(self.java_ssl_socket.getInputStream())
     self._out_buf = BufferedOutputStream(self.java_ssl_socket.getOutputStream())
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from java.io import BufferedOutputStream as BO
from java.io import BufferedInputStream as BI
from java.io import FileInputStream as FI
from java.io import FileOutputStream as FO

f_read = FI("file1.txt")
b_read = BI(f_read)

f_write = FO("file2.txt")
b_write = BO(f_write)

while True:
    ch = b_read.read()
    if ch != -1:
        b_write.write(ch)
    else:
        break

b_read.close()
f_read.close()
b_write.close()
f_write.close()