How to insert a youtube video as an attachment to specified timeline item? - google-mirror-api

Currently attachment takes stream for the content, is it possible to set a youtube video url for the attachment?
Thanks

This is not yet possible with the current version of the API and Glass client. Feel free to file a feature request on our issues tracker.

It is possible to stream a youtube video in the timeline card, here is the C#.Net code. use this name space "YoutubeExtractor".This works fine for me. When getting the youtube video url get the link that comes after you select share.
private static String InsertItem5(MainController controller)
{
string link = "http://youtu.be/9uYKISlL7Vg";
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
String vLink = video.DownloadUrl;
TimelineItem critical = new TimelineItem()
{
Text = "Menu Card",
BundleId = "666",
Notification = new NotificationConfig() { Level = "DEFAULT" },
MenuItems = new List<MenuItem>()
{
new MenuItem() {Action = "DELETE"},
}
};
String mediaLink = vLink;
if (!String.IsNullOrEmpty(mediaLink))
{
Stream stream = null;
if (mediaLink.StartsWith("/"))
{
stream = new StreamReader(controller.Server.MapPath(mediaLink)).BaseStream;
}
else
{
HttpWebRequest request = WebRequest.Create(mediaLink) as HttpWebRequest;
request.UseDefaultCredentials = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
byte[] b = null;
using (Stream streamFromWeb = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = streamFromWeb.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (streamFromWeb.CanRead && count > 0);
b = ms.ToArray();
stream = new MemoryStream(b);
}
}
controller.Service.Timeline.Insert(critical, stream, "video/mp4").Upload();
}
else
{
controller.Service.Timeline.Insert(critical).Fetch();
}

Related

View files in j2ee web application using fancybox and google doc viewer

I have a java servlet that serves files from s3. These files can be either image, pdf or doc/docx. I have to implement a feature in my web application to display these files in google doc viewer.
In my case, I am not able to send content so that google doc viewer reads it and displays the file. (when shouldDownload == Binary.YES).
This the code I have that downloads the file from s3 and set it in my bean class -
ApplicantzFileModel document = (ApplicantzFileModel) MongoSelectRogueModel
.selectOneById(ApplicantzFileModel.class, id);
Binary shouldDownload = Binary.valueOf(download);
if (document != null) {
if (shouldDownload == Binary.YES) {
docBean.fileStream = document.downloadFileStream();
docBean.fileName = document.getFileName();
docBean.isFileDownloadResponse = true;
} else {
File file = document.downloadFile();
if (file != null) {
String content = null;
content = FileHandler.read(file);
if (content != null) {
docBean.fileContent = content;
docBean.fileName = document.getFileName();
}
}
}
docBean.actionSuccess = true;
docBean.isFileContentResponse = true;
}
This is the code in my doGet/doPost to serve the response -
if (bean.isFileDownloadResponse) {
OutputStream responseOutputStream;
try {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "inline; filename=" + bean.fileName);
responseOutputStream = response.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = bean.fileStream.read(buf)) != -1) {
responseOutputStream.write(buf, 0, len);
}
responseOutputStream.flush();
responseOutputStream.close();
bean.fileStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
response.setContentType("application/msword");
response.addHeader("Content-disposition", "inline; filename=" + bean.fileName);
responseStr = bean.fileContent;
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
if (writer != null) {
writer.println(responseStr);
writer.flush();
writer.close();
}
}
And this is the html code in my frontend to open google doc viewer in fancybox -
"<a data-fancybox="" data-type="iframe" data-src="http://docs.google.com/viewer?url=http%3A%2F%2Fsomeserver.com%2Fapplication%2Fdocument%3Faction%3Dget%26id%3Dsomeid%26download%3DYES&embedded=true" href="javascript:void(0);" data-doc-id="someid">My Link</a>"
Or more specifically, google doc viewer url that opens up -
var innerurl = encodeURIComponent('http://someserver.com/application/document?action=get&id='+this.docId+'&download=YES');
this.docUrl = 'http://docs.google.com/viewer?url='+innerurl+'&embedded=true';
I am not able to open the word or pdf document in my fancybox. Can someone please suggest what to do to serve files via Java.

Converting byte[] to pdf, rotating 180 degrees, back to byte[] and to response.outputstream

I am trying to rotate a pdf document 180 degrees. Stored as a byte[] initially, it should be returned to the same, so that I can write it to the outputstream to our customers. This is my working code without rotation:
if (pdfurl == null)
return View(errorview);
var response = Response;
var getbyteresult = WebService.GetPDFAsByteArray(pdfurl);
MemoryStream ms = new MemoryStream(getbyteresult);
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("content-disposition",
"attachment;filename=label.pdf");
response.Buffer = true;
ms.WriteTo(response.OutputStream);
response.End();
return View("~/Views/Order/pdf.cshtml");
I've tried several libraries (itext, freesharp, spire), none of correctly manipulates and outputs.
Thanks in advance,
Rasmus Edvardsen
EDIT: The language is C#, and it's an MVC web application.
EDIT2: John's answer solved my problem - I also had an outdated verison of itextsharp, so that answers why most other solutions I tried failed the same way.
Never meant to come off as arrogant or anything, but I realise that's how it came out. Sorry and thanks.
Looking at your sample code it seems to me that you are using C# so here's a spoon feed for you.
Using iTextSharp:
private byte[] RotatePDF(byte[] pdfBytes, int rotation)
{
byte[] renderedBytes = null;
using (MemoryStream ms = new MemoryStream())
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, ms);
PdfReader pdfReader = null;
PdfStamper stamper = null;
try
{
document.Open();
pdfReader = new PdfReader(pdfBytes);
stamper = new PdfStamper(pdfReader, ms);
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
PdfDictionary pageDict = pdfReader.GetPageN(i);
PdfNumber pdfRotation = pageDict.GetAsNumber(PdfName.ROTATE);
if (pdfRotation != null)
{
rotation += pdfRotation.IntValue;
rotation %= 360;
}
pageDict.Put(PdfName.ROTATE, new PdfNumber(rotation));
}
pdf.AddDocument(pdfReader);
pdfReader.Close();
}
catch (Exception)
{
renderedBytes = null;
}
finally
{
if (pdfReader != null)
{
pdfReader.Close();
}
if (document != null)
{
document.Close();
}
}
renderedBytes = ms.ToArray();
return renderedBytes;
}
}
Usage:
var getbyteresult = WebService.GetPDFAsByteArray(pdfurl);
getbyteresult = RotatePDF(getbyteresult, 180); // 90 180 270 360

Displaying image from database in iTextSharp document [duplicate]

I try to create a PDF report from a datatable. One of the columns contents image. How can I extract the image from datatable and insert into PDF table? I'm using iTextShap version 5.4.2.0. Here is the code:
public void Report(DataTable dt, string output)
{
Document doc = new Document(PageSize.LETTER, 50, 50, 80, 50);
PdfWriter PDFWriter = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
iTextSharp.text.Font hel8 = FontFactory.GetFont(BaseFont.HELVETICA, 8);
doc.Open();
PdfPTable table = new PdfPTable(dt.Columns.Count);
float[] widths = new float[] { 1.2f, 1.2f, 1.2f, 1.2f, 1f, 4f, 1f, 4f };
table.SetWidths(widths);
table.WidthPercentage = 100;
PdfPCell cell = new PdfPCell(new Phrase("NewCells"));
cell.Colspan = dt.Columns.Count;
foreach (DataColumn c in dt.Columns)
{
table.AddCell(new Phrase(c.ColumnName, hel8));
}
foreach (DataRow r in dt.Rows)
{
if (dt.Rows.Count > 0)
{
table.AddCell(new Phrase(r[0].ToString(), hel8));
table.AddCell(new Phrase(r[1].ToString(), hel8));
table.AddCell(new Phrase(r[2].ToString(), hel8));
table.AddCell(new Phrase(r[3].ToString(), hel8));
table.AddCell(new Phrase(r[4].ToString(), hel8));
table.AddCell(new Phrase(r[5].ToString(), hel8));
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drwaing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi); <-- this is the problem code
table.AddCell(img);
table.AddCell(new Phrase(r[7].ToString(), hel8));
}
}
doc.Add(table);
}
doc.Close();
}
Update: #nekno, all of your suggestions are worked.
But I still need to correct the casting at line:
byte[] byt = (byte[])r[6];
It gave me a casting exception from VS2008. So I added the conversion function (pulled it from stackoverflow):
byte[] ImageToByte(System.Drawing.Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
And revised the code:
byte[] byt = ImageToByte((System.Drawing.Image)dt.Rows[e][6]);
Thanks.
What exactly is the problem? What happens when you use your problem code?
Try one of the other Image.GetInstance() overloads:
You can pass the byte array directly:
byte[] byt = (byte[])r[6];
Image img = Image.GetInstance(byt);
Or you can pass the Stream:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
Image img = Image.GetInstance(ms);
Or you can give iTextSharp more info about the image format:
byte[] byt = (byte[])r[6];
MemoryStream ms = new MemoryStream(byt);
System.Drawing.Image sdi = System.Drawing.Image.FromStream(ms);
Image img = Image.GetInstance(sdi, ImageFormat.Png);
If your column can be cast to a System.Drawing.Image, then you can use it directly:
Image img = Image.GetInstance((System.Drawing.Image)r[6], System.Drawing.Imaging.ImageFormat.Png);
I have suggested steps how shows how to add image into PDF, given below code snippet show how to add logo into your PDF using iTextsharp, follow provided below steps:
I have provided link to download "itextsharp" component from given link http://sourceforge.net/projects/itextsharp/
You have to add reference into your application.
Next you have to add required namespaces "iTextsharp.text.html", "iTextsharp.text" to consume its best properties.
Now you have to add code snippet into your application given at the end, add code snippet under "button click" in code behind.
Hope it will work for you !!!
protected void btnPDF_Click(object sender, ImageClickEventArgs e)
{
DataTable dtn = new DataTable();
dtn = GetDataTable();
dtPDF = dtn.Copy();
for (int i = 0; i <= dtn.Rows.Count - 1; i++)
{
ExportToPdf(dtPDF);
}
}
public void ExportToPdf(DataTable myDataTable)
{
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
pdfDoc.Add(p);
string clientLogo = Server.MapPath(".") + "/logo/tpglogo.jpg";
string imageFilePath = Server.MapPath(".") + "/logo/tpglogo.jpg";
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
//Resize image depend upon your need
jpg.ScaleToFit(80f, 60f);
//Give space before image
jpg.SpacingBefore = 0f;
//Give some space after the image
jpg.SpacingAfter = 1f;
jpg.Alignment = Element.HEADER;
pdfDoc.Add(jpg);
Font font8 = FontFactory.GetFont("ARIAL", 7);
DataTable dt = myDataTable;
if (dt != null)
{
//Craete instance of the pdf table and set the number of column in that table
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
//PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (DocumentException de)
{
System.Web.HttpContext.Current.Response.Write(de.Message);
}
catch (IOException ioEx)
{
System.Web.HttpContext.Current.Response.Write(ioEx.Message);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

Writing byte array to GAE Blobstore

I'm able to read the bytes and print it out on System console. However since GAE does not support file creation, I search through StackOverflow and found out that I can write into GAE blobstore. But I'm not sure how to go about doing it as I'm new to GAE..
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=UTF-8");
// resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
// out.println("<html><body>");
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("<br />Got a form field: " + item.getFieldName());
} else {
out.println("<br />Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName());
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream( in ));
ZipEntry entry;
// Read each entry from the ZipInputStream until no
// more entry found indicated by a null return value
// of the getNextEntry() method.
byte[] buf = new byte[10244];
int len;
while ((entry = zis.getNextEntry()) != null) {
out.println("Unzipping: " + entry.getName());
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile("text/plain");
boolean lock = false;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
PrintWriter outter = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
StringBuilder sb = new StringBuilder(buf.length);
if (entry.getName().equalsIgnoreCase("booking.csv")) {
int count = 0;
while ((len = zis.read(buf, 0, buf.length)) != -1) {
//I'm trying to write byte[] into blobstore instead of printing using
//System.out.write(buf, 0, len);
}
Any advice?
Try this:
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
while ((len = zis.read(buf, 0, buf.length)) != -1) {
writeChannel. write(ByteBuffer.wrap(buf, 0, len), null);
}
Easiest way:
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;
...
// your data in byte[] format
byte[] data = image.getData();
/**
* MIME Type for
* JPG use "image/jpeg" for PNG use "image/png"
* PDF use "application/pdf"
* see more: https://en.wikipedia.org/wiki/Internet_media_type
*/
String mimeType = "image/jpeg";
// save data to Google App Engine Blobstore
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(mimeType);
FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
writeChannel.write(java.nio.ByteBuffer.wrap(data));
writeChannel.closeFinally();
// your blobKey to your data in Google App Engine BlobStore
BlobKey blobKey = fileService.getBlobKey(file);
// THANKS TO BLOBKEY YOU CAN GET FOR EXAMPLE SERVING URL FOR IMAGES
// Get the image serving URL (in https:// format)
String imageUrl =
ImagesServiceFactory.getImagesService().getServingUrl(
ServingUrlOptions.Builder.withBlobKey(blobKey
).secureUrl(true));

Uploading a file by Console Application asp.net

i've searched about how to upload files to websites using console applications and i reached some ways, seems like the correct way, but i'm not having sucess with this. So i need some help!
First, the solution that i've founded follows:
class Program
{
static void Main(string[] args)
{
//Program.Test1();
Program.Test3();
Console.ReadLine();
}
public static void Test3()
{
//Set this to dont get an Invalid Request Exception
System.Net.ServicePointManager.Expect100Continue = false;
//Set a real page for this test
string url = "http://www.toledorocket.com/perftest/uploadtest/fileselect.asp";
string[] files = { "C:\\Documents and Settings\\wkurten\\Desktop\\fogao.txt" }; //Put some real file
NameValueCollection nvc = new NameValueCollection();
nvc.Add("FILE1", "fogao.txt");
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" +
boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials =
System.Net.CredentialCache.DefaultCredentials;
//Is you have an connection with proxy, uncomment and set the values bellow:
/*NetworkCredential localNetworkCredential = new NetworkCredential("user", "pass", "domain");
httpWebRequest2.Proxy = new WebProxy("server:port", false);
httpWebRequest2.Proxy.Credentials = localNetworkCredential;*/
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "file" + i, files[i]);
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
}
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
//Gets the response
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//Retrieve the html from response
string htmlResponse = reader2.ReadToEnd();
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
}
}
The problem that i'm having with this solution is that when i upload a file and retrieves the WebResponse, the page that i'm getting is the page with the upload form and not the page that appears after upload, that page with the success message.
On the page that i'm trying to upload the file i have this html/form:
<FORM METHOD="POST" ENCTYPE="multipart/form-data" ACTION="uploadstatus.asp">
<INPUT TYPE="FILE" SIZE="40" NAME="FILE1"> <INPUT TYPE=SUBMIT VALUE="Upload!">
</FORM>
When i run my code i just get this same form every time, seems like i'm never posting anything... anyone have an idea of what is happening?

Resources