Зверь-чародей
Шива стал умнее - больше не хочет Diary ID, что логично, и теперь выдает ссылки на сделанные записи.
Скажите, вы бы заинтересовались, если бы Шива стал opensource? Вам это пригодилось бы?
Скажите, вы бы заинтересовались, если бы Шива стал opensource? Вам это пригодилось бы?
Делать Шиву opensource имеет смысл тогда, если есть желающие поставить его на свой хостинг и/или дополнять его код.
По поводу клиентов - дневники поддерживают MetaWeblog API и к ним подходит куча клиентов. Новости читать надо diary-spirit.diary.ru/p45708516.htm
package ryotsuke;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
// ??????? ?????, ??????? ?????????????? ? ???????
import javax.microedition.rms.RecordStore;
// ? ????????? URL ? ??????? ?? ????? ????????? ? ???
import javax.microedition.rms.RecordStoreException;
// ??? ??????. ???? ???????? ??? ???????????? ?????????
// ??????? ?????, ??? ????????????? HTTP ??????????.
public class Shiva extends MIDlet {
private Display display;
private Command exitCommand =
new Command("Выход", Command.EXIT, 1);
private Command okCommand =
new Command("Санкра", Command.OK, 1);
private Command cancelCommand =
new Command("Назад", Command.CANCEL, 1);
private URLEntry mainForm;
/** string buffer for assembling HTTP requests. */
StringBuffer buffer = new StringBuffer();
private String DoPost(HttpConnection cnc, PostDat post) throws IOException {
buffer = new StringBuffer();
HttpConnection c = cnc;
InputStream is = null;
OutputStream os = null;
String res="Результат:";
//res+=post.getString();
int status = 0;
try {
//c = (HttpConnection)Connector.open(url);
// Set the request method and headers
c.setRequestMethod("POST"); // ставим метод соединения
c.setRequestProperty("Connection","close");
c.setRequestProperty("User-Agent","bot"); // юзер агент
c.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
c.setRequestProperty("Accept","text/plain");
// Getting the output stream may flush the headers
os = c.openOutputStream();
os.write(post.getString().getBytes());
//os.flush(); // Optional, openInputStream will flush
// Get the status code, causing the connection to be made
status = c.getResponseCode();
// Any 500 status number (500, 501) means there was a server error
if ((status == HttpConnection.HTTP_NOT_IMPLEMENTED) ||
(status == HttpConnection.HTTP_VERSION) ||
(status == HttpConnection.HTTP_INTERNAL_ERROR) ||
(status == HttpConnection.HTTP_GATEWAY_TIMEOUT) ||
(status == HttpConnection.HTTP_BAD_GATEWAY)) {
System.err.print("WARNING: Server error status [" + status + "] ");
System.err.println("returned for parameters ["+post.getString()+"]");
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (c != null) {
c.close();
}
return "Failed connection";
}
// Only HTTP_OK (200) means the content is returned.
if (status != HttpConnection.HTTP_OK) {
throw new IOException("Response status not OK [" + status + "]");
}
// Open the InputStream and get the ContentType
is = c.openInputStream();
String type = c.getType();
processType(type);
// Get the length and process the data
int len = (int)c.getLength();
if (len > 0) {
byte[] data = new byte[len];
int actual = is.read(data);
process(data);
} else {
int ch;
while ((ch = is.read()) != -1) {
process((byte)ch);
}
}
setKarma(post.getKarma());
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (c != null) {
c.close();
}
}
res += new String(buffer);
return res;
}
/**
* Process the type.
* @param type that type
*/
void processType(String type) {
}
/**
* Process the data one character at a time.
* @param b one byte of data
*/
void process(byte b) {
buffer.append((char)b);
}
/**
* Process the data from the array.
* @param b an array of bytes.
*/
void process(byte[] b) {
for (int i = 0; i < b.length; i++) {
process(b[i]);
}
}
private String getKarma() {
try {
RecordStore rs = RecordStore.openRecordStore("KARMA", true);
if (rs.getNumRecords() > 0) {
String s = "shiva";
try {
s = new String(rs.getRecord(1), "UTF-8");
} catch (UnsupportedEncodingException ex) {
displayError(new Throwable(ex.toString()), mainForm);
}
rs.closeRecordStore();
return s;
}
} catch (RecordStoreException ex) {
displayError(new Throwable(ex.toString()), mainForm);
}
return "shiva";
}
private void setKarma(String k) {
try {
RecordStore rs = RecordStore.openRecordStore("KARMA", true);
try {
if (rs.getNumRecords() > 0) {
rs.setRecord(1, k.getBytes("UTF-8"), 0, k.getBytes("UTF-8").length);
} else
rs.addRecord(k.getBytes("UTF-8"), 0, k.getBytes("UTF-8").length);
} catch (UnsupportedEncodingException ex) {
displayError(new Throwable(ex.toString()), mainForm);
}
rs.closeRecordStore();
} catch (RecordStoreException ex) {
displayError(new Throwable(ex.toString()), mainForm);
}
}
public Shiva() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
exitMIDlet();
}
protected void pauseApp() {
}
protected void startApp()
throws MIDletStateChangeException {
if (display == null) {
initMIDlet();
}
}
private void initMIDlet() {
display = Display.getDisplay(this);
mainForm = new URLEntry();
displayError(new Throwable("Hi!"), mainForm);
display.setCurrent(mainForm);
}
public void exitMIDlet() {
notifyDestroyed();
}
// ????????? ???????????? ??? ??????????? ?????????????? ????????.
void displayError(Throwable e, Displayable next) {
Alert a = new Alert("Ошибка");
a.setString(e.toString());
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, next);
}
// ???????? ?? ???????????? URL ????? ???????.
class URLEntry extends Form
implements CommandListener {
private String url="ryotsuke.com/other/shiva/webpost.php";
private TextField karmaTF;
private TextField titleTF;
private TextField textTF;
private TextField tagsTF;
private ChoiceGroup postCG;
private StringItem str;
URLEntry() {
super("Шива");
addCommand(exitCommand);
addCommand(okCommand);
str = new StringItem("Info: ","строка запроса");
karmaTF = new TextField("Карма-код", "shiva", 200, TextField.ANY);
karmaTF.setString(getKarma());
titleTF = new TextField("Заголовок", "", 200, TextField.ANY);
textTF = new TextField("Текст сообщения", "", 2000, TextField.ANY);
tagsTF = new TextField("Тэги", "", 500, TextField.ANY);
postCG = new ChoiceGroup("Постить в:", 2); //Choise.MULTIPLE
postCG.append("LiveJournal", null);
postCG.append("Дневники", null);
postCG.append("Плюрк", null);
postCG.setSelectedFlags(new boolean[]{true, true, true});
append(karmaTF);
append(titleTF);
append(textTF);
append(tagsTF);
append(postCG);
//append(str);
setCommandListener(this);
}
public void commandAction(Command c,
Displayable d) {
if (c == exitCommand) {
exitMIDlet();
} else if (c == okCommand) {
try {
PostDat pst = new PostDat();
pst.setTitle(titleTF.getString());
pst.setText(textTF.getString());
pst.setTags(tagsTF.getString());
pst.setKarma(karmaTF.getString());
boolean[] res=new boolean[3];
postCG.getSelectedFlags(res);
pst.l=res[0];
pst.d=res[1];
pst.p=res[2];
HttpConnection conn =
(HttpConnection)Connector.open( url+"?"+pst.getString());
display.setCurrent(
new Logger( this, conn, pst) );
} catch (IOException e) {
displayError(e, this);
}
}
}
}
class Logger extends Form
implements Runnable, CommandListener {
private Displayable next;
private HttpConnection conn;
private PostDat pstDt;
private StringItem text =
new StringItem( null, "" );
Logger( Displayable next,
HttpConnection conn, PostDat d ){
super( "Познание" );
this.next = next;
this.conn = conn;
pstDt=d;
addCommand( cancelCommand );
setCommandListener( this );
append( text );
Thread t = new Thread( this );
t.start();
}
public void commandAction( Command c,
Displayable d ){
display.setCurrent( next );
try {
conn.close();
}
catch( IOException e ){
displayError( e, next );
}
}
public void run(){
update( "Отправка. Молитесь. ");
try {
update( DoPost(conn, pstDt));
}
catch( IOException e ){
update( "Ошибка: " +
e.toString() );
}
}
void update( String line ){
if( display.getCurrent() != this ) return;
String old = text.getText();
StringBuffer buf = new StringBuffer();
buf.append( old );
if( old.length() > 0 ){
buf.append( '\n' );
}
buf.append( line );
text.setText( buf.toString() );
}
}
}
class PostDat {
private String title;
private String text;
private String tags;
private String karma;
public boolean l;
public boolean d;
public boolean p;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getString()
{
return "karma="+EncodeURL(karma)+"&title="+EncodeURL(title)+"&text="+EncodeURL(text)+"&tags="+EncodeURL(tags)+"&l="+(l?"1":"0")+"&d="+(d?"1":"0"+"&p=")+(p?"1":"0");
}
public String getKarma() {
return karma;
}
public void setKarma(String karma) {
this.karma = karma;
}
private String EncodeURL(String URL) {
if(URL==null)return "";
StringBuffer s = new StringBuffer();
int temp;
for (int i = 0; i < URL.length(); i++) {
temp = URL.charAt(i);
if (temp == ' ') {
s.append('+');
} else if (temp <= 0x7f) {
s.append((char) temp);
} else if (temp - 896 <= 0xbf) {
s.append("%d0");
s.append('%').append(Integer.toHexString(temp - 896));
} else if (temp - 960 <= 0x8f) {
s.append("%d1");
s.append('%').append(Integer.toHexString(temp - 960));
}
}
return s.toString();
}
}